Laravel 12 – Display Real-Time Notifications with Toastr.
Laravel 12 – Display Real-Time Notifications with Toastr.
In this tutorial, we will learn how to integrate Toastr notifications in Laravel 12, showing real-time success, error, info, and warning messages with routes, controller, and master layout for smooth user feedback.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide walks you through adding Toastr notifications to a Laravel project. After creating a fresh Laravel 12 application, you’ll generate a ToastrController to manage different message types, including success, error, info, and warning. A master.blade.php layout is then set up to display these notifications consistently across your app, with Tailwind CSS for styling and Toastr for interactive alerts. Next, you define routes in web.php to trigger each notification type, providing an organized way to handle user feedback. Finally, by running the Laravel development server, you can test the notifications in real time, with each button displaying the appropriate message, ensuring a smooth and responsive user experience.
Step # 1 : Get Your Laravel 12 Project Ready.
To get started, you’ll need a Laravel 12 application. You can either create a fresh project or continue with one you already have. If the Laravel Installer is available globally on your machine, you can quickly scaffold a new application using this command.
laravel new toastr
In case the Laravel Installer is not installed, you can create the project using Composer instead.
composer create-project laravel/laravel --prefer-dist toastr
When you create the project using Composer, Laravel skips the interactive setup and simply generates a clean application. Any configuration can be handled later if needed. If you use the Laravel Installer instead, you’ll be guided through a short setup wizard. When the installer asks for input, follow the prompts using the options below.
- Starter Kit: Choose None to start with a clean, unopinionated setup.
- Testing Framework: Select Pest for a modern and expressive testing experience.
- Database: Pick MySQL as the default database for the project.
- Run Migration: Type yes to run the default migrations immediately.
- Frontend Dependencies: Choose Yes to install all required frontend packages automatically.
After the setup finishes, you’ll have a clean Laravel 12 project with Pest ready for testing, MySQL configured as the default database, frontend dependencies installed, and the default migrations already executed.
Step # 2 : Move into the Project Directory.
Open your terminal (for example, Git Bash) and navigate to the root directory of your Laravel project using the following command.
cd c:xampp/htdocs/toastr
Once inside the project directory, you can run Artisan, Composer, and other Laravel commands without issues.
Step # 3 : Create the Toastr Controller.
Next, generate a controller that will be responsible for triggering different Toastr notifications. Run the following Artisan command.
php artisan make:controller ToastrController
This creates a new ToastrController.php file inside the app/Http/Controllers directory. Now, open the controller and add methods for each type of Toastr message.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ToastrController extends Controller
{
// Store a success message in the session and redirect back
public function success()
{
return redirect()->back()->with('success', 'Operation was successful!');
}
// Store an error message in the session and redirect back
public function error()
{
return redirect()->back()->with('error', 'An error occurred!');
}
// Store an info message in the session and redirect back
public function info()
{
return redirect()->back()->with('info', 'Here is some information!');
}
// Store a warning message in the session and redirect back
public function warning()
{
return redirect()->back()->with('warning', 'This is a warning!');
}
}
Each method stores a Toastr message type in the session and immediately redirects the user back to the previous page. When the frontend loads, Toastr checks the session for any messages and displays the corresponding notification. This provides users with instant, clear feedback about their actions, whether an operation succeeded, failed, or just provides information, making the app feel more interactive and responsive.
Step # 4 : Set Up a Master Layout for Toastr Notifications.
To make your application consistent and avoid repeating code, it’s a good idea to create a master layout that handles Toastr notifications. This layout will act as the main template, which other views can extend, ensuring that notifications work everywhere automatically. Create a new file called master.blade.php inside your resources/views directory and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shotcut - Toastr Notifications</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Toastr CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
</head>
<body class="bg-gray-800 text-gray-100 min-h-screen flex flex-col items-center justify-center">
<div class="max-w-3xl w-full p-10 bg-gray-900 rounded-xl shadow-2xl text-center">
<h1 class="text-4xl font-bold mb-8">Code Shotcut - Toastr Notifications</h1>
<div class="grid grid-cols-2 gap-6">
<!-- Triggers a success Toastr message -->
<a href="{{ route('toastr.success') }}" class="px-6 py-3 bg-green-600 hover:bg-green-700 rounded-lg shadow-md font-semibold transition">
Show Success
</a>
<!-- Triggers an error Toastr message -->
<a href="{{ route('toastr.error') }}" class="px-6 py-3 bg-red-600 hover:bg-red-700 rounded-lg shadow-md font-semibold transition">
Show Error
</a>
<!-- Triggers an info Toastr message -->
<a href="{{ route('toastr.info') }}" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded-lg shadow-md font-semibold transition">
Show Info
</a>
<!-- Triggers a warning Toastr message -->
<a href="{{ route('toastr.warning') }}" class="px-6 py-3 bg-yellow-500 hover:bg-yellow-600 rounded-lg shadow-md font-semibold transition">
Show Warning
</a>
</div>
<p class="mt-6 text-gray-400">
Click any button above to see the corresponding Toastr notification appear in real-time.
</p>
</div>
<!-- jQuery & Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<!-- Display Toastr notifications based on session messages -->
<script>
@if(session('success'))
toastr.success("{{ session('success') }}");
@elseif(session('error'))
toastr.error("{{ session('error') }}");
@elseif(session('info'))
toastr.info("{{ session('info') }}");
@elseif(session('warning'))
toastr.warning("{{ session('warning') }}");
@endif
</script>
</body>
</html>
By including Tailwind CSS and Toastr.js in the master.blade.php layout, you ensure that notifications can appear on any page with consistent styling. Tailwind takes care of the layout and design of the buttons and containers, while Toastr handles the actual notifications. This way, triggering success, error, info, or warning messages is simple, consistent, and improves the overall user experience across your application.
Step # 5 : Set Up Routes for Toastr Notifications.
Now it’s time to define routes that will trigger the different Toastr messages. Open the web.php file and add routes that point to the respective methods in your ToastrController.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ToastrController;
// Main page using the master layout
Route::get('/', function () {
return view('master');
});
// Routes for different Toastr notifications
Route::get('/success', [ToastrController::class, 'success'])->name('toastr.success');
Route::get('/error', [ToastrController::class, 'error'])->name('toastr.error');
Route::get('/info', [ToastrController::class, 'info'])->name('toastr.info');
Route::get('/warning', [ToastrController::class, 'warning'])->name('toastr.warning');
Each route points to a specific method in the ToastrController, so visiting a URL like /success or /error will display the corresponding notification. This setup keeps your routes clean and organized, making it simple to handle all your Toastr messages in one place while ensuring consistent feedback for users across the app. With this structure, adding new notification types in the future is quick and straightforward, keeping your code easy to maintain.
Step # 6 : Test Your Toastr Notifications.
Now it’s time to see everything in action. Start the Laravel development server by running.
php artisan serve
Then, open your browser and go to: http://127.0.0.1:8000.
Click the buttons on the page to trigger different notifications. Each button is linked to a specific route and will display a corresponding Toastr message, success, error, info, or warning. This allows you to instantly see feedback for each action, giving users clear, visual confirmation of what just happened and helping ensure your app communicates effectively.
Conclusion
By following this guide, you’ve successfully added Toastr notifications to your Laravel application. This approach offers a straightforward way to provide real-time feedback, helping users understand the outcome of their actions through clear success, error, info, and warning messages. The setup is easy to follow and can be customized to match your app’s design and requirements. Whether you want to enhance user interaction or deliver instant notifications, Toastr is a reliable and effective solution for any Laravel project.
For more details and advanced options, check out the official Toastr documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments