How to Use Flash Messages in Laravel 12 with Example

How to Use Flash Messages in Laravel 12 with Example

In this example, I would like to show you how to add flash messages in a Laravel 12 application. We will utilize Bootstrap 5 alerts for displaying flash messages, including success, error, warning, and info.

We will define various types of flash message notifications like alert-success, alert-danger, alert-info, and alert-warning messages, in Bootstrap Laravel 12 projects. When you have a successful task on the controller method, you can use a success flash message; if you encounter an error task, you can use an error flash message.

Laravel Development Services

Flash messages are required in the Laravel 12 application because that way we can give alerts regarding what progress is complete, errors, warnings, etc. In this tutorial, I will cover several ways to give a flash message, such as redirecting with a success message, redirecting with an error message, redirecting with a warning message, and redirecting with an info message. In this example, we use a Bootstrap flash alert layout, which enhances the overall layout.

So, you just have to follow the basic three steps to integrate flash messages into your Laravel 12 application. Let’s follow the steps below:

Steps to Use Flash Message in Laravel 12:

Step 1: Create Global File For Flash Message

In the first step, we will create a new Blade file flash-messages.blade.php. In this file, we will write the code for the Bootstrap alert and check which messages come.

The following alerts will be added:

  • Success
  • Error
  • Warning
  • Info
  • Validation Error

So, let’s create flash-messages.blade.php file and put the code below in that file.

resources/views/layouts/flash-messages.blade.php

@session('success')
<div class="alert alert-success alert-dismissible fade show" role="alert">
    {{ $value }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endsession
      
@session('error')
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    {{ $value }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endsession
       
@session('warning')
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    {{ $value }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endsession
       
@session('info')
<div class="alert alert-info alert-dismissible fade show" role="alert">
    {{ $value }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endsession
      
@if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Please check the form below for errors</strong>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif

Step 2: Use Flash Message in Theme

In this step, we have to include the flash-messages.blade.php file in your theme’s default file. You just have to include this flash file in your default theme blade file as below:

@include('flash-messages')

You can also see that I added a flash file to my theme, so that you can add it that way. Let’s see an example below:

resources/views/layouts/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
  
    <title>{{ config('app.name', 'Laravel') }}</title>
  
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">
  
    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>
  
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">
  
                    </ul>
  
                    ...

                </div>
            </div>
        </nav>
        <main class="py-4">
  
            @include('layouts.flash-messages')
  
            @yield('content')

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

Step 3: Use Flash Messages with Redirect

In this step, we will learn how to give a message when you redirect one by one.

Redirect with success message

We can simply redirect a route or redirect a URL or redirect back with a success flash message. We can use it in the controller like this:

<?php  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        $this->validate($request,[
            'name' => 'required',
            'email' => 'required',
            'password' => 'required'
        ]);

        $user = User::create($request->all());

        return back()->with('success', 'User created successfully!');
    }
}

Redirect with error message

We can simply redirect the route or redirect the URL or redirect back with an error flash message. We can use it in the controller like this:

<?php   
namespace App\Http\Controllers;   
use Illuminate\Http\Request;
   
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect()->route('home')
                         ->with('error', 'Something is wrong!');
    }
}

Redirect with warning message

We can simply redirect the route or redirect the URL or redirect back with a warning flash message. We can use it in the controller like this:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect()->route('home')
                         ->with('warning', 'User email required!');
    }
}

Redirect with info message

We can simple redirect route or redirect url or redirect back with info flash message, we can use in controller like this way:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect()->route('home')
                         ->with('info', 'User fetched successfully!');
    }
}

Validation Error

If you use laravel 5 validation then you will redirect back with errors automatically, At that time it will also generate error flash message.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        $this->validate($request,[
            'name' => 'required',
            'email' => 'required',
            'password' => 'required'
        ]);

        ...
    }
}

This way you can simple implement flash message in your laravel 12 application.

Conclusion

Flash messages in Laravel 12 are incredibly useful for improving user interaction and experience. With just a few lines of code, you can deliver timely feedback to users on various actions they perform on your site.

Hire laravel Developer

Whether you’re building contact forms, login systems, or CRUD operations, flash messages are a simple yet effective addition.

FAQ

  1. What is Laravel?

With its expressive and elegant syntax, Laravel is a web application framework that offers a starting point and foundation for PHP web application development.

  1. Why Use Laravel?

Laravel has a rich set of features, including an expressive database abstraction layer (Eloquent), powerful templating engine (Blade), built-in authentication and authorization, routing system, queues, scheduled jobs, and a command-line interface (Artisan CLI). It is focused on developer experience and provides many tools to facilitate development.

  1. What are flash messages in Laravel?

Session-based flash messages are used to give users one-time notifications (such as informational, error, or success messages) that are automatically removed after only one display.

Previous Article

How to Add Tooltip for Specific Payment Method on Checkout Page?

Next Article

Write Cleaner Laravel Code Using the when() Helper

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨