Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

Any advice appreciated.

like image 703
harryg Avatar asked Jan 08 '14 19:01

harryg


People also ask

What is the best use of flash sessions in laravel?

Flash messages is required in laravel application because that way we can give alter with what progress complete, error, warning etc. In this tutorial i added several way to give flash message like redirect with success message, redirect with error message, redirect with warning message and redirect with info message.

What is flash message in laravel?

A flash message is used to communicate back to the user of the website or application that an event has taken place. Often times you'll see a redirect with flash message. This may be something the user intended to do, or it might be something that is just informational.

What is flash data in laravel?

Summary. Flashing data to the session stores short-lived data and can display it in the application. It is usually used to display status after an action. RELATED TAGS. laravel.


1 Answers

One solution would be to flash two variables into the session:

  1. The message itself
  2. The "class" of your alert

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 :) )

like image 150
msturdy Avatar answered Oct 19 '22 21:10

msturdy