Reputation: 1494
I am having problems with my session flash message
I have a simple logic like this
if(empty($code))
{
return redirect()->back()->with('modal', 'working');
}
And in my view file I am doing alert for testing
@if(session('modal'))
<script>
alert('working');
</script>
@endif
The problem is this alert('working');
gets executed two times. So, when it's redirecting back, one time it immediately executes and second time, it executes after loading document.
I tried various workarounds like deleting session key, loading on document ready for javascript, but nothing works.
What could be the issue?
Upvotes: 3
Views: 3492
Reputation: 2645
Assuming you're using bootstrap...
Here is how I'd approach it:
Within your views make a new folder named: alerts and within that make a file named alerts.blade.php
Paste:
@if (Session::has('success'))
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ Session::get('success') }}
</div>
@elseif (Session::has('error'))
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ Session::get('error') }}
</div>
@elseif(Session::has('warning'))
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ Session::get('warning') }}
</div>
@endif
Within each file you have, you can now use: include('alerts.alerts')
Now within your controller, if you wish to flag an error/warning or success message simply use:
Session::flash('success', 'Success message here')
return redirect()->back();
Session::flash('error', 'Error message here')
return redirect()->back();
Session::flash('warning', 'warning message here')
return redirect()->back();
This way you don't have to keep adding HTML to every page that will hold any kind of message as you can simply just include one file which will flag up when called.
The initial make up seems a bit long winded I know but ultimately it'll save you a lot of time
Upvotes: 4
Reputation: 1246
You should user laravel flash helper like this,
$request->session()->flash('status', 'Task was successful!');
return back();
Upvotes: 0