Click to share! ⬇️

laravel flash message

We all know what Flash Messages are. Almost every single modern website uses them in one form or another. 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. The key to remember about flash messages is that they are not persistent. In other words, they are used on a one off basis type of scenario. The modern Front End Frameworks have all kinds of styling built into classes for working with Flash Messages. In this episode, we’ll take a look at using Laravel to power some Flash Messages in the style of Twitter Bootstrap. Onward!

Flash Container

First up, we need to consider where we are going to display the flash messages. Usually, you can place a div as a placeholder right in a master page. Therefore, all of your actual views will extend the master page, and will have access to the div so that flash messages could easily be displayed anywhere in your application. Read up on Blade in Laravel if you need a refresher on how to set up your master page.

This will be our master page which will hold our container:
default.blade.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Laravel Flash Message Tutorial</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>

<body>

<div class="container">

  <div>
    <h1>Laravel Flash Messages</h1>
  </div>

@if ( Session::has('flash_message') )

  <div class="alert {{ Session::get('flash_type') }}">
      <h3>{{ Session::get('flash_message') }}</h3>
  </div>
  
@endif

@yield('content')

</div>
</body>
 
</html>

Based on User Actions

Flash messages are typically generated based on actions the user takes. They may also be sent a flash message to query the user if she is sure that she wants to take an action. Think of a scenario like when your friends challenge you to try the hottest hot sauce on earth while you are out having chicken wings with them. Your good friend might jump in and give you a flash message like, “Hold Up Friend! Are you sure you want to render your mouth useless for a week?!” You get the idea.

Here we will just whip up a fictitious application that has four simple actions a user can take. They can login, edit, cancel, and delete their account. Every time the user takes an action, they will simply be redirected back to the home page. In fact for the purposes of this demonstration, the home view is the *only* view in the entire app. This will kind of hammer home the idea of how flash messages actually work.

Session::flash()

There are a couple of ways to do this, but the first approach will make use of Session::flash(). Ok, here is our little application so far:
routes.php

Route::get('/login', function()
{
	// Log in the user, blah blah...
	
	Session::flash('flash_message', '<b>Well done!</b> You successfully logged in to this website.');
	Session::flash('flash_type', 'alert-success');
	
    return Redirect::to('home');
});

Route::get('/edit', function()
{
	// User can edit their profile here...
	
	Session::flash('flash_message', '<b>Heads up!</b> You just made a cool edit to your profile.');
	Session::flash('flash_type', 'alert-info');
	
    return Redirect::to('home');
});

Route::get('/cancel', function()
{
	// User can cancel their membership here...
	
	Session::flash('flash_message', '<b>Warning!</b> You are about to cancel your membership.');
	Session::flash('flash_type', 'alert-warning');
	
    return Redirect::to('home');
});

Route::get('/delete', function()
{
	// User can delete their account here...
	
	Session::flash('flash_message', '<b>Oh Snap!</b> Are you sure you want to delete your account?');
	Session::flash('flash_type', 'alert-danger');
	
    return Redirect::to('home');
});


Route::get('home', function()
{
	Return View::make('home');
});

So what do we have here? Well, each route is an example of completing the action that the name of the route infers, setting a flash message, and then redirecting the user back to the home page.

All Views Inherit From default.blade.php

So we have our master page set up, which includes some links to external content delivery networks to make it easy to have access to the twitter bootstrap classes we’ll use in this episode. We also include an if clause to check if there is a flash message present so that we will only display the message once. When will the flash message display? The flash message will display only during the initial redirect to the home page. Once you start reloading the home page, the flash session is cleared, and you will not see any message. Here is our home view:

home.blade.php

@extends('layouts.default')

@section('content')

<div class="col-lg-8">

<h1>{{ link_to('/login', 'login') }} <small> {{ link_to('/home', 'go home') }} </small></h1>

<h1>{{ link_to('/edit', 'edit') }} <small> {{ link_to('/home', 'go home') }} </small></h1>

<h1>{{ link_to('/cancel', 'cancel') }}  <small> {{ link_to('/home', 'go home') }} </small></h1>

<h1>{{ link_to('/delete', 'delete') }}  <small> {{ link_to('/home', 'go home') }} </small></h1>

</div>

@stop

So what we can see here is that home.blade.php extends layouts.default. layouts.default actually refers to the file name of default.blade.php so be sure to keep that in mind. In this home view, we just make use of some simple linking mechanisms to easily click between the home page, and the various user actions of login, edit, cancel, and delete. What should happen then in this application is the following. Any time the user clicks on any of the action related items, the flash will be set, and when Laravel redirects the user to the home page, it will do so with the flash message which will get displayed on that initial page load. Simply clicking the go home link will refresh the page and clear any flash messages. Let’s test it out:

Logging In

http://localhost/laratut/public/login
laravel flash message success

Edit Profile

http://localhost/laratut/public/edit
laravel flash message info

Cancel Membership

http://localhost/laratut/public/cancel
laravel flash message warning

Delete Account

http://localhost/laratut/public/delete
laravel flash message danger

Cool! Now anytime you click on the go home links, the home page will load and there will be no flash message. This is because, the flash message is only for the initial page load.

Flash Messages via Chaining

In true Laravel form, there is more than one way to accomplish something. In the case of Flash Messages, we saw that by using Session::flash(), we were able to put a message into the flash session so that we could access in our views on a one off basis. Then we could make use of Session::has() and Session::get() to create our messages. If you prefer the method chaining style of syntax, you could just as easily create your Flash Message Sessions using ->with() like this:

Route::get('/login', function()
{
	// Log in the user, blah blah...
	
    return Redirect::to('home')
	  ->with('flash_message', '<b>Well done!</b> You successfully logged in to this website.')
	  ->with('flash_type', 'alert-success');
});

Route::get('/edit', function()
{
	// User can edit their profile here...

    return Redirect::to('home')
	  ->with('flash_message', '<b>Heads up!</b> You just made a cool edit to your profile.')
	  ->with('flash_type', 'alert-info');
});

Route::get('/cancel', function()
{
	// User can cancel their membership here...

    return Redirect::to('home')
	  ->with('flash_message', '<b>Warning!</b> You are about to cancel your membership.')
	  ->with('flash_type', 'alert-warning');
});

Route::get('/delete', function()
{
	// User can delete their account here...

    return Redirect::to('home')
	  ->with('flash_message', '<b>Oh Snap!</b> Are you sure you want to delete your account?')
	  ->with('flash_type', 'alert-danger');
});


Route::get('home', function()
{
	Return View::make('home');
});

Testing out this new method of applying our flash data has the same effect. In addition, when we visit or reload the home page, we can see that no message is displayed, just as we intended.

laravel flash message with

The Flashing Takeaway

Do you have to use Flash Messages in your applications? Of course not, but they are a really nice way to give guidance to the user during their navigation of your website or application. Personally, I am a big fan of using Flash Messages. They did confuse me at first, but now that we have crushed this tutorial together, working with Flash Messages in Laravel couldn’t be easier!

Click to share! ⬇️