In this guide, we'll see how to add flash messages in laravel 10. In this step-by-step guide, we'll explore adding Flash Messages to your Laravel 10 and Laravel 11 applications.
In this article, we'll display different kinds of messages like success, error, warning, and info. we'll create a straightforward example where a flash message appears when a specific action is executed.
How to create Flash Message in Laravel 10 and Laravel 11
If you haven't already installed Laravel, you can do so using Composer:
composer create-project laravel/laravel flash-messages-example
Create a controller to handle the logic for your flash messages. Run the following command to generate a new controller:
php artisan make:controller FlashMessageController
Define routes in the routes/web.php
file to handle the display of flash messages. Open the file and add the following:
use App\Http\Controllers\FlashMessageController;
Route::get('/flash-message', [FlashMessageController::class, 'index']);
Route::post('/process-action', [FlashMessageController::class, 'processAction']);
Open the FlashMessageController.php
file generated in Step 2 and add the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FlashMessageController extends Controller
{
public function index()
{
return view('flash-message');
}
public function processAction(Request $request)
{
// Flash message example
$request->session()->flash('success', 'Action successful!');
return redirect('/flash-message');
}
public function create(Request $request)
{
return redirect()->route('index')
->with('error','Something want wrong!');
}
public function create(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required'
]);
$users = User::create($request->all());
return back()->with('info','Email address is already exist!');
}
}
Create a new Blade view file named flash-message.blade.php
in the resources/views
directory and add the following content:
<!DOCTYPE html>
<html>
<head>
<title>Flash Message Example Techsolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ></script>
</head>
<body>
@if(session('success'))
<div style="background-color: #4CAF50; color: white; padding: 10px;">
{{ session('success') }}
</div>
@endif
<form action="/process-action" method="post">
@csrf
<button type="submit">Perform Action</button>
</form>
</body>
</html>
Run the Laravel development server:
php artisan serve
You might also like: