In this guide, I will show you how to display flash messages in Laravel 11 using Livewire 3. Flash messages are temporary notifications that inform users about the success or failure of an action, such as form submission or file uploads.
Livewire makes it easy to show these messages dynamically without requiring page reloads.
Step-by-Step Guide to Flash Messages in Laravel 11 with Livewire 3
If you haven’t already set up Laravel 11, install it using:
composer create-project laravel/laravel livewire-flash
cd livewire-flash
Next, I install Livewire 3 in my Laravel project:
composer require livewire/livewire
I generate a Livewire component to demonstrate flash messages:
php artisan make:livewire FlashMessage
This creates two files:
app/Livewire/FlashMessage.php
(Component class)resources/views/livewire/flash-message.blade.php
(Component view)
I open app/Livewire/FlashMessage.php
and update it:
namespace App\Livewire;
use Livewire\Component;
class FlashMessage extends Component
{
public $message;
public function showMessage()
{
session()->flash('success', 'Action completed successfully!');
}
public function showError()
{
session()->flash('error', 'Something went wrong!');
}
public function render()
{
return view('livewire.flash-message');
}
}
I open resources/views/livewire/flash-message.blade.php
and add the UI:
<div>
@if (session()->has('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
@if (session()->has('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<button wire:click="showMessage" class="btn btn-success">Show Success Message</button>
<button wire:click="showError" class="btn btn-danger">Show Error Message</button>
</div>
I add the Livewire component to resources/views/welcome.blade.php
or any other Blade file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel Livewire Flash Messages</title>
@livewireStyles
</head>
<body>
<div class="container">
<h1>Laravel 11 Livewire 3 Flash Messages</h1>
<livewire:flash-message />
</div>
@livewireScripts
</body>
</html>
I start the Laravel development server using:
php artisan serve
You might also like:
In this article, we will see how to install angular in ubuntu. Angular is a framework, library, assets, a...
May-09-2022
Today we will see how to download file on the ftp server using php. Many time we have requirment to retrieve file from t...
May-21-2021
In this article, we will see the laravel 9 left join query example. laravel 9 left join eloquent returns all rows from t...
Mar-31-2022
In this tutorial, we will learn laravel 8 socialite login with facebook account, as you all know currently many websites...
Mar-08-2021