Laravel 12 Flash Message: Step by Step Guide

Hey! In this article, I’ll show you how I use flash messages in Laravel 12 to show success or error alerts after actions like form submission, login, or update.

Flash messages are stored in the session and automatically cleared after the next request. They’re perfect for giving users quick feedback like “User created successfully” or “Something went wrong.”

Laravel 12 Flash Message: Step by Step Guide

Laravel 12 Flash Message: Step by Step Guide

 

Step 1: Set Flash Message in Controller

Here’s how I set a success message after creating a user:

return redirect()->back()->with('success', 'User created successfully.');

Or for errors:

return redirect()->back()->with('error', 'Something went wrong.');

 

Step 2: Display Message in Blade View

Add this code to your resources/views/layouts/app.blade.php or wherever you want to show alerts:

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

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

You can also use alert-warning or alert-info classes for other types of messages.

 

Step 3: Optional - Add Auto-Close with jQuery

If you want the alert to disappear after a few seconds, add this script:

<script>
    setTimeout(function () {
        $(".alert").fadeOut("slow");
    }, 3000); // 3 seconds
</script>

Hope this helped! Save this snippet, you’ll need it often while building Laravel apps.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS