Session put does not seem to be working properly - php

I'm working with Laravel 5.8 and I wanted to make sure that users can submit a form only every 2 hours (as long as a session is alive).
So I tried this at the Controller:
if(Session::has('request_has_been_sent')){
return redirect()->back()->with('error', 'You just submitted a request and cannot submit a new one');
}else{
$withDraw = WithdrawWallet::create([
'balance_value' => $request->balance_wallet,
'can_draw' => $request->can_draw,
'shaba_number' => $request->shaba_number,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'description' => $request->desc,
'status' => 'pending',
'user_id' => auth()->user()->usr_id,
]);
Session::put('request_has_been_sent');
}
return redirect()->back()->with('success','Your request was sent');
So by this, everytime a user submits a new request, session request_has_been_sent must be set.
Therefore at the next time user submits the form, if the session was still alive, the message You just submitted a request and cannot submit a new one appears.
But now the problem is it does not work. In fact user can still submit another request, right after submitting a request.
This means that the session is not set somehow.
So what's going wrong here? How can I properly do this?

You can set session using set and put method
Session::put('name','value');
Retrieve it using get
Session::get('name')
So in your case you need to set your session use
Session::put('request_has_been_sent','yes');
And to check if it is set or not use
if(Session::get('request_has_been_sent')){
Docs: https://laravel.com/docs/5.0/session

I think your only problem here is not setting the session value to anything you need to set it to something or else laravel will ignore it.
Session::put('request_has_been_sent', true);
// Check if it exists, this will check if it exists without getting it
Session::has('request_has_been_sent')

Once the user is logged out al the user sesion wil be flushd out. Which means user and create and WithdrawWallet and logout and then login again and then user can create another WithdrawWallet so to fix that you can use cache
$cacheKey = WithdrawWallet::class.'.'.auth()->user()->usr_id;
if (Cache::has($cacheKey)) {
return redirect()->back()->with('error', 'You just submitted a request and cannot submit a new one');
} else {
$withDraw = Cache::remember($cacheKey, now()->addHours(2), function () use ($request){
return WithdrawWallet::create([
'balance_value' => $request->balance_wallet,
'can_draw' => $request->can_draw,
'shaba_number' => $request->shaba_number,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'description' => $request->desc,
'status' => 'pending',
'user_id' => auth()->user()->usr_id,
]);
});
}
return redirect()->back()->with('success', 'Your request was sent');

Related

How to fix status code 303 in codeigniter?

I am working on CI 3 when I post form data and insert into database then form a value that has been successfully save and I am also getting the last insert through $insert_id = $this->db->insert_id() following example as mention below:
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => sha1($this->input->post('cpassword')),
'confirm_id' => sha1($this->input->post('email')),
'created_at' => date('Y-m-d H:i:s')
);
$success = $this->db->insert('instructor', $data);
$insert_id = $this->db->insert_id($success);
if($success == true)
{
$instructorData = $this->instructor_m->get_instructorData($insert_id);
$this->session->set_userdata('InstloginuserId',$instructorData->instructorID);
redirect(base_url('board'));
}
else
{
$this->session->set_flashdata('message', $this->lang->line('fail'));
redirect(base_url('register'));
}
If success condition is true then it redirects to board page but it throws status code: 303 I don't know why? Please help me to solve this.
The Session Library has been completely re-written in CodeIgniter 3 and now comes with a bunch of new features, but that also means that there are changes that you should make.
Read the Step 6: Update your Session library usage from CodeIgniter | Upgrading from 2.2.x to 3.0.x.

Testing Error messages to be shown for user

I'm trying to write a test to assert that my login page displays an error when the user enters an incorrect username or password.
#if ($errors->any())
<p>Looks like you’ve entered the wrong username or password.
<a href="{{route('password.request')}}">
Click here</a> to reset your password“ </p></div>
#endif
The functionality is working fine and I can see the errors on page, but for some reason, I can't get my test to pass.
->assertSessionHasErrors() is working fine, while ->assertSeeText() is not detecting the error messages in text.
`
public function userSeesErrorMessage() {
$user = factory('App\User')->create([
'password' => bcrypt($password = 'test'),
]);
$response = $this->followingRedirects()
->post('/login', [
'email' => $user->email,
'password' => 'incorrectPassword'
]);
$response->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');
}`
The response seem to contain the whole document's HTML, except for the part about the errors.
Any help would be much appreciated.
There might be a few reasons why this does does not work. Easiest thing you could do is to set a header for a referer. This way the validation will know where to redirect you back, because currently you're not submitting a form and the redirect is sending you to a page where you might not display the errors:
$response = $this->followingRedirects()
->post(
'/login',
[
'email' => $user->email,
'password' => 'incorrectPassword'
],
['referer' => '/login']
);
Another issue might be that the session errors are lost within the redirects, where you can try following the redirect separately:
$r = $this->post('/login', [
'email' => $user->email,
'password' => 'incorrectPassword'
]);
$r->assertStatus(302);
$r->assertSessionHasErrors('email');
$r = $this->followRedirects($r);
$r->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');

CodeIgniter - Checking user entered email once completed typing, to confirm if taken or not

Trying to perfect an email form input, where the user can enter their email that is to be associated to their account. However ideally, the system would reject/accept the entered email once they have finished typing (not on form submission). I am using CodeIgniter, and still learning alot unfortunately.
My VIEW/form has the following input:-
<?=form_input(array(
'name' => 'pi_email',
'id' => 'pi_email',
'value' => isset($email)?$email:'',
'maxlength' => '50',
'required' => 'yes',
'size' => '50',
'placeholder' => 'johndoe#example.com',
'class' => 'lg-textbox'
));?>
On the controller/profile, I have the below as a test to try and catch these inputs and echo if taken or not, right now option 1 is always displayed as "email already taken", when they are not actually. I have seen the below form_validation online, however I do not generally understand the context in which it is to be used successfully
$this->form_validation->set_rules($new_email, 'Email', 'required|valid_email|is_unique[tbl_users.email]');
if($this->form_validation->run() == false){
echo "email already taken";
} else {
echo "Valid email!";
}
How could i implement real time check that will display on screen? I know how to use db model to run a query and return results, if = 0 valid, if > 0 then email taken? can this be implemented on the view or has to be done in the controller and then return user to the profile page and display an error message?
Any assistance, general pointing in the right direction would be great

Save() not passing anything in my id field

My debug value is set to 2 and I think because there's no data being passed here I'm getting a validation error, which is why this was first appearing to be a phantom error. I'm not sure though as I'm still new to Cakephp.
I have an Addresses controller that is passing data to my model that looks like so:
public function add() {
if ($this->request->is('post')) {
$this->Address->create();
if ($this->Address->save($this->request->data)) {
$this->Session->setFlash(__('The address has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The address could not be saved. Please, try again.'));
}
}
$users = $this->Address->User->find('list');
$this->set(compact('users'));
}
However when I debug using die(debug($this->request->data)))) I get the following result, revealing that there is nothing being passed in my id field:
/app/Controller/AddressesController.php (line 61)
array(
'Address' => array(
'id' => '',
'building_number' => '1',
'street_name' => 'Test Street',
'city' => 'Cityville',
'post_code' => 'N113AQ',
'user_id' => '1'
)
)
Any ideas as to why nothing is being passed into the id field? I have controllers working in exactly the same way for different tables that go off perfectly fine.
My Address.id field in my database is set to auto increment and is named correctly, $this->Address->save() returns false too.
If $this->request->data contains an array element named after the form’s model, and that array contains a empty value of the model’s primary key(here the id), then the FormHelper will create an add form for that record. For add method HTTP POST verb is ok. POST is for create and PUT is for edit in CakePHP. You can check validations and change the request type to non-GET. It may work.
if (!$this->request->is('get')){
//Save logic here
}

CodeIgniter - Can't load view after loading model

i am exploring codeigniter for quite some time and most of the problem i faced while exploring it already solved by googling it but the problem i am facing right now is kind of weird. So here is the situation. I have a controller which will validate the form and pass all input from the form to the model using array if there is no error after the validation.
I have another function in the same controller which will send out email upon called. So what i wanted to do is validate the form, sent all input using array to model and insert it into the database then send email to the user's email address.
Below is part of the code from signup controller :
if($this->form_validation->run() == FALSE){
//load custom config
$this->config->load('site_config', TRUE);
$this->load->library('session');
$this->load->helper('form');
//retrieve data
$data['site_title'] = $this->config->item('site_title', 'site_config');
$data['site_login'] = $this->config->item('site_login', 'site_config');
$data['site_url'] = $this->config->item('site_url', 'site_config');
$data['img_folder_path'] = $this->config->item('img_folder_path', 'site_config');
$this->load->view('view_header', $data);
$this->load->view('view_signup',$data);
$this->load->view('view_footer');
}else{
$this->load->model('Adduserinfointoactivationtable');
$user_infos = array('first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'tel' => $this->input->post('tel'),
'fax' => $this->input->post('fax'),
'add_1' => $this->input->post('add_1'),
'add_2' => $this->input->post('add_2'),
'city' => $this->input->post('city'),
'post_code' => $this->input->post('post_code'),
'state' => $this->input->post('state'),
'password' => sha1($this->input->post('pass_2')),
'activation_code' => sha1(sha1($this->input->post('email').$this->input->post('pass_2'))),
);
$this->Adduserinfointoactivationtable->addUserInfo($user_infos);
$this->send_mail();
}
Here is the model :
public function addUserInfo ($user_infos){
$sql = "INSERT INTO tbl_user_Account (email_add, activation_code, fname, lname, tel, fax, add1, add2, city, post_code, state, password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);";
$query = $this->db->query($sql, array($user_infos['email'], $user_infos['activation_code'], $user_infos['first_name'], $user_infos['last_name'], $user_infos['tel'], $user_infos['fax'], $user_infos['add_1'], $user_infos['add_2'], $user_infos['city'], $user_infos['post_code'], $user_infos['state'], $user_infos['password']));
$query->result_array();
}
when i place the $this->send_mail(); right after the else, it works. I did some testing and the email function is working fine. but when i call it this way which is after $this->Adduserinfointoactivationtable->addUserInfo($user_infos);, it doesn't send out email. I also noticed no matter what i do after $this->Adduserinfointoactivationtable->addUserInfo($user_infos);, for example load a view or echo out something, it doesn't work.
Can someone advice me on this?
I think your issue might be the fact that, according to the CodeIgniter documentation, $this->db->query() returns a boolean value if an "insert" type query is performed.
This is happening in your case. Because of this, you're probably creating a fatal error by executing $query->result_array().
As a simple fix, you can probably try the following:
if (is_object($query)) {
return $query->result_array();
} else {
return $query;
}
You are not loading any view in the else part, are you? Do a redirect to the same function or to a success function page.

Categories