I\'m making my first app in Laravel and am trying to get my head around the session flash messages. As far as I\'m aware in my controller action I can set a flash message ei
I usually do this
in my store() function i put success alert once it saved properly.
\Session::flash('flash_message','Office successfully updated.');
in my destroy() function, I wanted to color the alert red so to notify that its deleted
\Session::flash('flash_message_delete','Office successfully deleted.');
Notice, we create two alerts with different flash names.
And in my view, I will add condtion to when the right time the specific alert will be called
@if(Session::has('flash_message'))
<div class="alert alert-success"><span class="glyphicon glyphicon-ok"></span><em> {!! session('flash_message') !!}</em></div>
@endif
@if(Session::has('flash_message_delete'))
<div class="alert alert-danger"><span class="glyphicon glyphicon-ok"></span><em> {!! session('flash_message_delete') !!}</em></div>
@endif
Here you can find different flash message stlyes Flash Messages in Laravel 5
One solution would be to flash two variables into the session:
for example:
Session::flash('message', 'This is a message!');
Session::flash('alert-class', 'alert-danger');
Then in your view:
@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif
Note I've put a default value into the Session::get()
. that way you only need to override it if the warning should be something other than the alert-info
class.
(that is a quick example, and untested :) )
If you want to use Bootstrap Alert to make your view more interactive. You can do something like this:
In your function:-
if($author->save()){
Session::flash('message', 'Author has been successfully added');
Session::flash('class', 'success'); //you can replace success by [info,warning,danger]
return redirect('main/successlogin');
In your views:-
@if(Session::has('message'))
<div class="alert alert-{{Session::get('class')}} alert-dismissible fade show w-50 ml-auto alert-custom"
role="alert">
{{ Session::get('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
My way is to always Redirect::back() or Redirect::to():
Redirect::back()->with('message', 'error|There was an error...');
Redirect::back()->with('message', 'message|Record updated.');
Redirect::to('/')->with('message', 'success|Record updated.');
I have a helper function to make it work for me, usually this is in a separate service:
function displayAlert()
{
if (Session::has('message'))
{
list($type, $message) = explode('|', Session::get('message'));
$type = $type == 'error' : 'danger';
$type = $type == 'message' : 'info';
return sprintf('<div class="alert alert-%s">%s</div>', $type, message);
}
return '';
}
And in my view or layout I just do
{{ displayAlert() }}