In Laravel, the best way to pass different types of flash messages in the session
Clash Royale CLAN TAG#URR8PPP
In Laravel, the best way to pass different types of flash messages in the session
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 either by going
Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK?
For the case of redirecting to another route, or
Session::flash('message', 'This is a message!');
In my master blade template I'd then have:
@if(Session::has('message'))
<p class="alert alert-info"> Session::get('message') </p>
@endif
As you may have noticed I'm using Bootstrap 3 in my app and would like to make use of the different message classes: alert-info
, alert-warning
, alert-danger
etc.
alert-info
alert-warning
alert-danger
Assuming that in my controller I know what type of message I'm setting, what's the best way to pass and display it in the view? Should I set a separate message in the session for each type (e.g. Session::flash('message_danger', 'This is a nasty message! Something's wrong.');
)? Then I'd need a separate if statement for each message in my blade template.
Session::flash('message_danger', 'This is a nasty message! Something's wrong.');
Any advice appreciated.
11 Answers
11
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.
Session::get()
alert-info
(that is a quick example, and untested :) )
Session::get()
Like most flash message solutions, this only deals with one message. So often, it is necessary to be able to fire off a bunch of messages, each maybe a different severity, and have them all displayed.
– Jason
Mar 11 '15 at 11:20
Here's what we are using in our projects gist.github.com/YavorK/7aa6e839dbe93e8854e4b033e31836a4
– Yavor Kirov
Aug 31 '16 at 8:06
This is so counter productive... Why is everyone upvoting this?
– Goowik
May 14 at 11:35
@Goowik - Saying its counter productive while not offering a more productive solution is counter productive.
– SupaMonkey
Aug 12 at 12:11
In your view:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert- $msg "> Session::get('alert-' . $msg) </p>
@endif
@endforeach
</div>
Then set a flash message in the controller:
Session::flash('alert-danger', 'danger');
Session::flash('alert-warning', 'warning');
Session::flash('alert-success', 'success');
Session::flash('alert-info', 'info');
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('
return '';
And in my view or layout I just do
displayAlert()
Great solution! Just want to say there's a typo on your closing div class where the " is missing (I cannot edit it as my edit has to be at least 6 characters...).
– Nicolas
Apr 11 '14 at 9:12
This is simply awesome but how does this work
$type = $type == 'error' : 'danger';
– overflow
Mar 25 '15 at 8:06
$type = $type == 'error' : 'danger';
Where do you put your helper in a seperate Helper Class?
– utdev
Jan 13 '17 at 9:02
Simply return with the 'flag' that you want to be treated without using any additional user function.
The Controller:
return Redirect::back()->withSuccess( 'Message you want show in View' );
Notice that I used the 'Success' flag.
The View:
@if( Session::has( 'success' ))
Session::get( 'success' )
@elseif( Session::has( 'warning' ))
Session::get( 'warning' ) <!-- here to 'withWarning()' -->
@endif
Yes, it really works!
You have a ton of typos in your answer, but your approach works great.
– Bat Lanyard
Aug 6 '15 at 3:41
If you work with Laravel 5, check out this package by laracasts:
https://github.com/laracasts/flash
thanks, i think this is the best solution :)
– simon
Aug 1 '15 at 18:52
You can make a multiple messages and with different types.
Follow these steps below:
app/Components/FlashMessages.php
namespace AppComponents;
trait FlashMessages
protected static function message($level = 'info', $message = null)
if (session()->has('messages'))
$messages = session()->pull('messages');
$messages = $message = ['level' => $level, 'message' => $message];
session()->flash('messages', $messages);
return $message;
protected static function messages()
return self::hasMessages() ? session()->pull('messages') : ;
protected static function hasMessages()
return session()->has('messages');
protected static function success($message)
return self::message('success', $message);
protected static function info($message)
return self::message('info', $message);
protected static function warning($message)
return self::message('warning', $message);
protected static function danger($message)
return self::message('danger', $message);
app/Http/Controllers/Controller.php
namespace AppHttpControllers;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateFoundationAuthAccessAuthorizesResources;
use AppComponentsFlashMessages;
class Controller extends BaseController
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
use FlashMessages;
This will make the FlashMessages
trait available to all controllers that extending this class.
FlashMessages
views/partials/messages.blade.php
@if (count($messages))
<div class="row">
<div class="col-md-12">
@foreach ($messages as $message)
<div class="alert alert- $message['level'] ">!! $message['message'] !!</div>
@endforeach
</div>
</div>
@endif
boot()
app/Providers/AppServiceProvider.php
namespace AppProviders;
use IlluminateSupportServiceProvider;
use AppComponentsFlashMessages;
class AppServiceProvider extends ServiceProvider
use FlashMessages;
public function boot()
view()->composer('partials.messages', function ($view)
$messages = self::messages();
return $view->with('messages', $messages);
);
...
This will make the $messages
variable available to "views/partials/message.blade.php
" template whenever it is called.
$messages
views/partials/message.blade.php
views/partials/messages.blade.php
<div class="row">
<p>Page title goes here</p>
</div>
@include ('partials.messages')
<div class="row">
<div class="col-md-12">
Page content goes here
</div>
</div>
You only need to include the messages template wherever you want to display the messages on your page.
use AppComponentsFlashMessages;
class ProductsController {
use FlashMessages;
public function store(Request $request)
self::message('info', 'Just a plain message.');
self::message('success', 'Item has been added.');
self::message('warning', 'Service is currently under maintenance.');
self::message('danger', 'An unknown error occured.');
//or
self::info('Just a plain message.');
self::success('Item has been added.');
self::warning('Service is currently under maintenance.');
self::danger('An unknown error occured.');
...
Hope it'l help you.
Another solution would be to create a helper class
How to Create helper classes here
class Helper
public static function format_message($message,$type)
return '<p class="alert alert-'.$type.'">'.$message.'</p>'
Then you can do this.
Redirect::to('users/login')->with('message', Helper::format_message('A bla blah occured','error'));
or
Redirect::to('users/login')->with('message', Helper::format_message('Thanks for registering!','info'));
and in your view
@if(Session::has('message'))
Session::get('message')
@endif
I don't know if I would recommend this approach since it's taking HTML out of the view and into code.
– Nick Coad
Sep 3 '14 at 4:28
For my application i made a helper function:
function message( $message , $status = 'success', $redirectPath = null )
$redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );
return $redirectPath->with([
'message' => $message,
'status' => $status,
]);
message layout, main.layouts.message
:
main.layouts.message
@if($status)
<div class="center-block affix alert alert-$status">
<i class="fa fa- $status == 'success' ? 'check' : $status"></i>
<span>
$message
</span>
</div>
@endif
and import every where to show message:
@include('main.layouts.message', [
'status' => session('status'),
'message' => session('message'),
])
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
You could use Laravel Macros.
You can create macros.php
in app/helpers
and include it routes.php.
macros.php
app/helpers
if you wish to put your macros in a class file instead, you can look at this tutorial: http://chrishayes.ca/blog/code/laravel-4-object-oriented-form-html-macros-classes-service-provider
HTML::macro('alert', function($class='alert-danger', $value="",$show=false)
$display = $show ? 'display:block' : 'display:none';
return
'<div class="alert '.$class.'" style="'.$display.'">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong><i class="fa fa-times"></i></strong>'.$value.'
</div>';
);
In your controller:
Session::flash('message', 'This is so dangerous!');
Session::flash('alert', 'alert-danger');
In your View
@if(Session::has('message') && Session::has('alert') )
HTML::alert($class=Session::get('alert'), $value=Session::get('message'), $show=true)
@endif
Not a big fan of the solutions provided (ie: multiple variables, helper classes, looping through 'possibly existing variables'). Below is a solution that instead uses an array as opposed to two separate variables. It's also easily extendable to handle multiple errors should you wish but for simplicity, I've kept it to one flash message:
Redirect with flash message array:
return redirect('/admin/permissions')->with('flash_message', ['success','Updated Successfully','Permission "'. $permission->name .'" updated successfully!']);
Output based on array content:
@if(Session::has('flash_message'))
<script type="text/javascript">
jQuery(document).ready(function()
bootstrapNotify('session('flash_message')[0]','session('flash_message')[1]','session('flash_message')[2]');
);
</script>
@endif
Unrelated since you might have your own notification method/plugin - but just for clarity - bootstrapNotify is just to initiate bootstrap-notify from http://bootstrap-notify.remabledesigns.com/:
function bootstrapNotify(type,title = 'Notification',message)
switch (type)
case 'success':
icon = "la-check-circle";
break;
case 'danger':
icon = "la-times-circle";
break;
case 'warning':
icon = "la-exclamation-circle";
$.notify(message: message, title : title, icon : "icon la "+ icon, type: type,allow_dismiss: true,newest_on_top: false,mouse_over: true,showProgressbar: false,spacing: 10,timer: 4000,placement: from: "top",align: "right",offset: x: 30,y: 30,delay: 1000,z_index: 10000,animate: enter: "animated bounce",exit: "animated fadeOut");
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Interesting, I didn't know about the default parameter for
Session::get()
That will come in super handy.– Nick Coad
Sep 3 '14 at 4:27