How to Display Session Flash Message in Laravel

Hello Artisan

In this tutorial i will show you how to display flash message notification in laravel 7. For showing laravel flash message i will use "laracasts/flash" package. You can do it with your own code without packages. But i will use this package for simplicity.

We need flash message to confirm our http request which we send it to server. Flash message helps us to know it works or not. If we get any error then flash message helps us to know it.

So let's see how to display session flash message in laravel.

 

Step 1 : Install Package

First of all install flash package via composer command. composer package offers a Twitter Bootstrap optimized flash messaging setup for your Laravel applications.

composer require laracasts/flash

 

Step 2 : Create Route

We need route show html form and submit it to database. So now paste this following code to create laravel flash message example.

routes/web.php

Route::get('/test', function(){
  return view('test');
})->name('test');

Route::post('/test', function(Request $request){
  \App\Test::create([
    'name' => $request->name
  ]);
  flash('Data submitted')->important();
  return redirect()->back();
});

 

Step 3 : Create Blade File

Now create test.blade.php to create html form where we will show our flash message after submitting the form to the server.

resources/views/test.blade.php

 

Now if you hit the submit button you will see the flash message. If you need to modify the flash message partials, you can run:

php artisan vendor:publish --provider="Laracasts\Flash\FlashServiceProvider"

 

Hiding Flash Messages

A common desire is to display a flash message for a few seconds, and then hide it. To handle this, write a simple bit of JavaScript. For example, using jQuery, you might add the following snippet just before the closing body tag.

 

You may also do:

flash('Message')->success(): Set the flash theme to "success".
flash('Message')->error(): Set the flash theme to "danger".
flash('Message')->warning(): Set the flash theme to "warning".
flash('Message')->overlay(): Render the message as an overlay.
flash()->overlay('Modal Message', 'Modal Title'): Display a modal overlay with a title.
flash('Message')->important(): Add a close button to the flash message.
flash('Message')->error()->important(): Render a "danger" flash message that must be dismissed.

 

Hope this laravel flash message tutorial can help you.