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
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.');
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.
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: