How To Work With Laravel Flash Messages

How To Work With Laravel Flash Messages


If you’ve come across a website with login/logout or any validation functions, chances are that you have probably come across Flash messages.

At the end of this tutorial, you should have at least a basic grasp of the following:

  • What Laravel Flash messages are
  • Examples of common scenarios where you may come across a flash message as a user
  • How to create Flash Messages in a Laravel Application
  • How to display beautiful flash messages using Materialize CSS toast notifications.

Laravel Flash messages are a kind of notification or feedback returned to a user as a response to the result of the action the user has taken. Some example of cases where a flash message is displayed in an application include:

  • When the user logged in successfully
  • When the user logged out successfully
  • After a user deletes an item from cart
  • After a user adds an item to his/her cart.
  • When an update to something has been successful.

Now, that you have an idea of what Flash Messages are, let’s get down into implementing them in a Laravel application.

Creating our Laravel Scaffolding

Run the command below to create a laravel project called laravel-toast and cd into it

composer create-project laravel/laravel laravel-toast && cd laravel-toast

Once the scaffolding has been generated, open it with your favorite editor and Let’s dive in.

Understanding how flash messages work in Laravel

Laravel ships with a Session class that contains a handful of methods. One of them is Session::flash() static method which handles sending and displaying flash messages on views.

To store a create a flash message the syntax is:

Session::flash('message', 'This is a flash message containing feedback to the user!'); 

The Session::flash() method carries two parameters: the name of our message which is a string and the content of the message which is a text.

Displaying Laravel Session Flash Messages in plain HTML

To display the flash message to the user we need to write an if statement in our blade file to check if there’s a flash message for the user and then to display it.

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

If you want to display the content of a Laravel flash message in your blade view, the syntax is siash_message}’}) </smilar to:

 @if ( Session::has('message') )
         
 <script> M.toast({html: '{{ Session::get('message') }}'}) </script>
                 
@endif

Laravel Flash messages Demo

To see this concept in real-time, let’s open up our project file in a code editor and modify the web.php file as thus:


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function(){
return  view('welcome');
});
Route::get('/login', function()
{
	// Log in the user and all that...
	
	Session::flash('flash_message', ' You successfully logged in to this website.');
	Session::flash('flash_type', 'alert-success');
	
    return Redirect::to('/');
});
 
Route::get('/edit', function()
{
	// User can edit their profile here...
	
	Session::flash('flash_message', 'You just made a cool edit to your profile.');
	Session::flash('flash_type', 'alert-info');
	
    return Redirect::to('/');
});
 
Route::get('/cancel', function()
{
	// User can cancel their membership here...
	
	Session::flash('flash_message', 'You are about to cancel your membership.');
	Session::flash('flash_type', 'alert-warning');
	
    return Redirect::to('/');
});
 
Route::get('/delete', function()
{
	// User can delete their account here...
	
	Session::flash('flash_message', 'Are you sure you want to delete your account?');
	Session::flash('flash_type', 'alert-danger');
	
    return Redirect::to('/');
});
 
 
// Route::get('home', function()
// {
// 	Return View::make('home');
// });

Next, create an app.blade.php file in your resources/views directory and add the following code to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Notifications</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
        {{-- <a class="btn" onclick="">Toast!</a> --}}
        <div class="container">
                <h1>Laravel Flash Messages with Materialize CSS Toasts</h1>
              </div>
             
            @if ( Session::has('flash_message') )
             
              <div class="alert {{ Session::get('flash_type') }}">
                <script> M.toast({html: '{{ Session::get('flash_message') }}', displayLegth: 1000, timeRemaining: 2000}) </script>
                  <h3></h3>
              </div>
              @endif
        @yield('content')    
    <footer>
        
    </footer>

</body>
</html>

Next, open up the default welcome.blade.php file in our resources/views directory and replace the default content with the code below.

@extends('app')
 
@section('content')
 
<div class="col-lg-12">
<a href="/login"> <button class="btn"> Logout</button></a>
<a href="/delete"> <button class="btn red"> Delete</button></a>
<a href="/cancel"> <button class="btn yellow"> Cancel</button></a>
<a href="/cancel"> <button class="btn blue"> Edit</button></a>

 
</div>
 
@endsection

Previewing Our Application

To preview our results, serve the application with php artisan serve command and on opening 127.0.0.1:8000 in the browser, our welcome page should look like this.

laravel flash messages

You can find the code uploaded on GitHub here:


Share on social media

//