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?
CodePudding user response:
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
CodePudding user response:
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')
CodePudding user response:
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');