I am working on an Online Store project using Laravel 5.8 and in this project I have added a checkbox for checking if user wants to pay the price by his online wallet:
<input class="form-check-input" type="checkbox" name="pay_wallet" value="1" id="defaultCheck2">
<label class="form-check-label small mr-3" for="defaultCheck2">
Pay with Wallet
</label>
Then at the Controller, I added this for submitting a session, if the user checked the checkbox:
try {
if ($request->pay_wallet == '1') {
Session::put('wallet', 'payment');
return redirect()->back();
}
}catch (\Exception $e) {
dd($e);
}
Then at the View, I tried this:
@php
if(session('wallet')){
$us_id = Auth()->user()->usr_id;
$user_wallet = App\UserWallet::where('user_id', $us_id)->get();
foreach($user_wallet as $uw){
echo "
<ul>
<li>$uw->id</li>
<li>$uw->balance</li>
</ul>
";
}
}
@endphp
Basically what I need to do here is to check, if the session wallet
was submitted, show all the available wallets based on his User Id.
But now the problem is, when I refresh the page, it still shows the wallets. Meaning that the session wallet
is still alive!
How can I solve this problem?
First, while we set Session, it will keep value till session is destroyed or you use Session::forget('wallet'). But you need that available for only once you load page.
For that you can use Laravel Flash message available by session. Replace your code with this:
try {
if ($request->pay_wallet == '1') {
return redirect()->back()->with(['wallet'=>'payment']);
}
}catch (\Exception $e) {
dd($e);
}
After that, when you set wallet flag like that. It will be only available for first time when you set then it will get deleted automatically :)