In Laravel, the best way to send different types of flash messages in a session

I am making my first application in Laravel and trying to figure out session flash messages. As far as I know in my control of the controller, I can install a flash message by going

Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK? 

In case of redirection to another route or

 Session::flash('message', 'This is a message!'); 

In my base blade template, I would have:

 @if(Session::has('message')) <p class="alert alert-info">{{ Session::get('message') }}</p> @endif 

As you may have noticed, I use Bootstrap 3 in my application and would like to use various message classes: alert-info , alert-warning , alert-danger , etc.

Assuming in my controller I know what message I am setting, what is the best way to pass and display it in a view? Should I set a separate message in the session for each type (for example, Session::flash('message_danger', 'This is a nasty message! Something wrong.'); )? Then I will need a separate if statement for each message in my blade template.

Any advice is appreciated.

+92
session laravel laravel-4
Jan 08 '14 at 19:02
source share
13 answers

One solution would be to run two variables in the session:

  • Message itself
  • The "class" of your alert

eg:

 Session::flash('message', 'This is a message!'); Session::flash('alert-class', 'alert-danger'); 

Then, in your opinion:

 @if(Session::has('message')) <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p> @endif 

Note. I put the default value in Session::get() . this way you only need to override it if the warning should be something other than the alert-info class.

(this is a quick example and untested :))

+155
Jan 08 '14 at 19:08
source share

In your opinion:

 <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 the 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'); 
+40
Sep 04 '14 at 3:57 on
source share

My way is to always redirect :: back to () 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 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() }} 
+32
Jan 08 '14 at 19:38
source share

Just go back with the β€œflag” you want to handle without using any additional user features. Controller:

 return \Redirect::back()->withSuccess( 'Message you want show in View' ); 

Notice that I used the Success flag.

View:

 @if( Session::has( 'success' )) {{ Session::get( 'success' ) }} @elseif( Session::has( 'warning' )) {{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' --> @endif 

Yes, it really works!

+11
Jan 29 '15 at 5:24
source share

You can create multiple posts with different types. Follow these steps:

  • Create a file: " app/Components/FlashMessages.php "
 namespace App\Components; 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); } } 
  1. On your base controller, " app/Http/Controllers/Controller.php ".
 namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesResources; use App\Components\FlashMessages; class Controller extends BaseController { use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests; use FlashMessages; } 

This will make the FlashMessages available to all controllers extending this class.

  1. Create a clip template for our posts: " 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 
  1. In the " boot() " method of " app/Providers/AppServiceProvider.php ":
 namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Components\FlashMessages; 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 for the " views/partials/message.blade.php " template whenever it is called.

  1. In your template, include our message template - " 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 a message template wherever you display messages on your page.

  1. On your controller, you can simply do this to push flash messages:
 use App\Components\FlashMessages; 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.'); } ... 

I hope he helps you.

+11
Jul 20 '16 at 3:22
source share

If you are working with Laravel 5, check out this package on laracasts:

https://github.com/laracasts/flash

+9
Feb 02 '15 at 13:25
source share

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 it.

 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 opinion

 @if(Session::has('message')) {{Session::get('message')}} @endif 
+6
Jan 08 '14 at 19:23
source share

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 :

 @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 each where to show the message:

 @include('main.layouts.message', [ 'status' => session('status'), 'message' => session('message'), ]) 
+4
Sep 04 '15 at 13:37
source share

You can use Laravel macros.

You can create macros.php in app/helpers and enable its route.php.

if you want to put your macros in a class file, 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">&times;</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 
+3
Jan 22 '15 at 7:41
source share

I usually do it

in my store () function, I will put a warning on successful completion.

 \Session::flash('flash_message','Office successfully updated.'); 

in my destroy () function, I wanted to color the red warning to notify that its remote

 \Session::flash('flash_message_delete','Office successfully deleted.'); 

Please note: we are creating two warnings with different flash names.

And, in my opinion, I will add a condition when a specific warning will be called at the right time

 @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 various flash messages stlyes Flash messages in Laravel 5

+3
Nov 26 '15 at 13:07 on
source share

Not a big fan of the provided solutions (that is: several variables, helper classes, loops on "possibly existing variables"). Below is a solution that uses an array instead, rather than two separate variables. It is also easily extensible to handle multiple errors if you want, but for simplicity, I saved it in a single flash message:

Redirection with an array of flash messages:

  return redirect('/admin/permissions')->with('flash_message', ['success','Updated Successfully','Permission "'. $permission->name .'" updated successfully!']); 

Output based on the contents of the array:

 @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 

Not relevant, as you can have your own notification method / plugin - but just for clarity - bootstrapNotify simply triggers a boot notification 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"}}); } 
+2
Aug 12 '18 at 12:52
source share

I think the following will work well with a smaller line of codes.

  session()->flash('toast', [ 'status' => 'success', 'body' => 'Body', 'topic' => 'Success'] ); 

I use a toaster, but you may have something similar in your opinion.

  toastr.{{session('toast.status')}}( '{{session('toast.body')}}', '{{session('toast.topic')}}' ); 
0
Jun 10 '19 at 8:54 on
source share

In the controller:

 Redirect::to('/path')->with('message', 'your message'); 

Or

 Session::flash('message', 'your message'); 

in Blade show the message in Blade As ur Desired Pattern:

 @if(Session::has('message')) <div class="alert alert-className"> {{session('message')}} </div> @endif 
0
Jul 19 '19 at 7:01
source share



All Articles