🔥 Laravel Implement Flash Messages Example – Complete Guide for Beginners

Flash messages are an essential part of modern web development. They help inform users about the result of an action they have performed—whether it's a successful form submission, a warning, or an error.

Laravel, being a developer-friendly PHP framework, makes it incredibly easy to implement flash messages using its built-in session system. In this tutorial, you’ll learn how to create, set, and display flash messages in Laravel step by step.


🧠 What Are Flash Messages in Laravel?

A flash message is a short-lived session message used to convey status or feedback to the user, such as:

  • ✅ “User created successfully!”
  • ❌ “Something went wrong. Please try again.”
  • ⚠️ “You are not authorized to perform this action.”

The key feature of a flash message is that it only persists for one request, and it automatically disappears after being displayed once.

Laravel provides a very simple way to handle flash messages using the session()->flash() method.


🚀 Let’s Build It Step-by-Step

We’ll implement flash messages using the following steps:

  1. Create a route and controller
  2. Add a flash message in the controller method
  3. Display the flash message in a Blade view
  4. Customize styling using Bootstrap (or your own CSS)
  5. Test the flash messages in the browser


✅ Step 1: Set Up a Route and Controller

First, create a route that will trigger a flash message via a controller.

👉 Add a route in routes/web.php:

use App\Http\Controllers\HomeController; Route::get('/', [HomeController::class, 'index'])->name('home');

👉 Now, generate the controller:

php artisan make:controller HomeController

This will create the controller file at:
app/Http/Controllers/HomeController.php


✅ Step 2: Set a Flash Message in the Controller

Open the HomeController and define the index() method to include a flash message:

📁 app/Http/Controllers/HomeController.php

namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function index() { // Set flash message session()->flash('alert-success', 'Welcome! This is a flash message.'); session()->flash('alert-class', 'alert-success'); // Redirect back to same route (for demonstration) return redirect()->route('home'); } }

Here’s what happens:

  • session()->flash('alert-success', '...') stores a success message for just the next request.
  • 'alert-class' can help you apply specific CSS styles (like Bootstrap alert colors).

You can also use multiple types of messages like alert-danger, alert-warning, or alert-info.


✅ Step 3: Display the Flash Message in the Blade View

Let’s now create a Blade view to render this flash message.

👉 Create a Blade view:

resources/views/home.blade.php

Here’s a robust example that checks for multiple types of messages and displays them with close buttons:

@extends('layout') @section('content') <h1>Laravel Flash Message Example</h1> @foreach (['danger', 'warning', 'success', 'info', 'secondary', 'primary', 'dark', 'light'] as $msg) @if(Session::has('alert-' . $msg)) <div class="alert alert-{{$msg}} d-flex align-items-center p-3 mb-4 alert-dismissible fade show" role="alert"> <div> {{ Session::get('alert-' . $msg) }} </div> <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button> </div> @endif @endforeach @endsection

This loop checks for session keys like alert-success, alert-danger, etc., and displays them accordingly using Bootstrap alerts.


✅ Step 4: Add Layout and Bootstrap Styling

If you don’t already have a layout.blade.php file, create one to wrap your content and include Bootstrap:

📁 resources/views/layout.blade.php

<!DOCTYPE html> <html> <head> <title>Laravel Flash Messages</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> @yield('content') </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html>

✅ Step 5: Testing the Flash Message

Now run your Laravel development server:

php artisan serve

Visit:
http://127.0.0.1:8000/

You should see the flash message displayed at the top of the page. If you refresh the page again, the message disappears — because flash messages only live for one request.


💡 Pro Tip: Use Flash Messages After Form Submissions

You’ll often use flash messages after form submissions (POST requests). Here’s how it works with form validation or model actions:

public function store(Request $request) { $validated = $request->validate([ 'name' => 'required', 'email' => 'required|email' ]); User::create($validated); return redirect()->route('users.index')->with('alert-success', 'User created successfully!'); }

And in the view:

@if(Session::has('alert-success')) <div class="alert alert-success">{{ Session::get('alert-success') }}</div> @endif

Or use Laravel's built-in helper:

@if(session('alert-success')) <div class="alert alert-success"> {{ session('alert-success') }} </div> @endif

📦 Optional: Flash Messages with Laravel Components (Reusable)

You can even make flash messages reusable using Laravel Blade components.

1. Create a component:

php artisan make:component Alert

Edit resources/views/components/alert.blade.php:

@props(['type' => 'success']) @if(session('alert-' . $type)) <div class="alert alert-{{ $type }} alert-dismissible fade show" role="alert"> {{ session('alert-' . $type) }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> @endif

Use it in your views like:

<x-alert type="success" /> <x-alert type="danger" />

🧩 Summary

Flash messages in Laravel are a simple yet powerful tool to enhance user experience by displaying quick notifications. Whether you’re confirming a successful action, showing validation errors, or alerting users to something important, flash messages are the go-to method.


✅ Recap:

  • Use session()->flash('key', 'value') to store flash data for the next request.
  • Flash messages are automatically removed after being displayed.
  • Display them in Blade views using conditional checks.
  • Use Bootstrap or custom styling to make them look great.
  • Ideal for feedback on form submissions, updates, and deletions.


📘 What’s Next?

Now that you’ve mastered flash messages, you can:

  • Combine with form validation to show success/error messages
  • Make reusable Blade components
  • Enhance UX with animations or auto-dismiss behavior

Want more tutorials? Visit From ZeroToDev for practical Laravel guides and tips.

Post a Comment

Previous Post Next Post

Contact Form