Laravel 11 - How to Integrate Toastr Notification

Touseef Afridi
15 Jan 25

Laravel 11 - How to Integrate Toastr Notification

In this tutorial, we will discuss how to use Toastr in Laravel 11 to display real-time notifications, enhancing user experience with instant 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 the process of integrating Toastr notifications in a Laravel project. After setting up a fresh Laravel project, you'll generate a ToastrController to handle different types of messages, including success, error, info, and warning. A master.blade.php layout will be created to consistently display these notifications across your application, with Toastr integrated alongside Tailwind CSS for a sleek and responsive design. You will then define routes in the web.php file to trigger each notification type, providing a structured way to manage user feedback. Lastly, by running the development server, you'll be able to test the Toastr notifications in action, displaying real-time messages when interacting with the different buttons for success, error, info, or warning notifications, ensuring a seamless user experience.

Step # 1 : Create a Fresh Laravel Project or Use an Existing Project.

If you have Laravel installed globally, use the following command to create a new Laravel project.
laravel new toastr
Or
Alternatively, if you do not have Laravel globally installed, use the Composer command.
composer create-project laravel/laravel --prefer-dist toastr
After running one of the above commands, follow these prompts.
  1. When asked to install the starter kit, select none.
  2. For the testing framework, choose Pest.
  3. When selecting a database, pick MySQL.
  4. When prompted to run the default database migration, select yes.

Once the installation is complete, your Laravel project will be ready for further configuration and development.

Step # 2 : Navigate to the Project Directory.

Open a terminal (e.g., Git Bash) and navigate to the Laravel project's root folder. Use the following command.
cd c:xampp/htdocs/toastr

Step # 3 : Generate a ToastrController.

Use the following command to create a new controller named ToastrController.
php artisan make:controller ToastrController
This command generates a new controller file inside the app/Http/Controllers directory, which can be used to handle application logic, manage requests, and return responses
Open ToastrController.php and add methods to trigger different types of Toastr message.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ToastrController extends Controller
{
    // Handles success messages
    public function success()
    {
        return redirect()->back()->with('success', 'Operation was successful!');
    }
    // Handles error messages
    public function error()
    {
        return redirect()->back()->with('error', 'An error occurred!');
    }
    // Handles informational messages
    public function info()
    {
        return redirect()->back()->with('info', 'Here is some information!');
    }
    // Handles warning messages
    public function warning()
    {
        return redirect()->back()->with('warning', 'This is a warning!');
    }
}
These methods store the Toastr message types in the session and redirect back to the previous page. The frontend then retrieves the session data and displays the appropriate notification using Toastr. This ensures that users receive immediate feedback based on their actions, improving the overall user experience and providing clear communication about the result of their interaction.

Step # 4 : Create a Master View for Toastr Notifications.

To efficiently manage your layout and include Toastr notifications across all pages, create a reusable view named master.blade.php. This master view will serve as the main layout, making it easy to extend in other views. By doing so, you ensure consistency across your application and reduce code duplication, as the same notification setup is automatically available in all pages that use this layout.
<!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 CDN -->
    <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-white min-h-screen flex items-center justify-center">
    <div class="container mx-auto px-4">
        <div class="flex justify-center">
            <div class="text-center">
                <h1 class="text-3xl font-bold mb-6">Code Shotcut - Toastr Notifications</h1>
                <div class="space-x-4">
                    <a href="{{ route('toastr.success') }}" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded shadow">Trigger Success</a>
                    <a href="{{ route('toastr.error') }}" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded shadow">Trigger Error</a>
                    <a href="{{ route('toastr.info') }}" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded shadow">Trigger Info</a>
                    <a href="{{ route('toastr.warning') }}" class="px-4 py-2 bg-yellow-500 hover:bg-yellow-600 text-white rounded shadow">Trigger Warning</a>
                </div>
            </div>
        </div>
    </div>
    <!-- jQuery and 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>
    <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>
Including the Toastr CDN links in the master.blade.php file ensures that Toastr notifications are available across all pages of your application. By loading the necessary CSS and JavaScript libraries globally in the master layout, you make it easy to trigger notifications on any page. This setup guarantees that the notifications are displayed consistently, regardless of the specific view or route the user is on. It helps maintain a seamless and uniform user experience, as feedback messages like success, error, info, or warning are readily accessible whenever needed, enhancing user interaction with the application.

Step # 5 : Define Routes.

In this step, you’ll update the web.php file to define routes that will trigger the various Toastr notifications. These routes will map to specific methods in the ToastrController and allow users to display different types of notifications based on the URL they visit.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ToastrController;
Route::get('/', function(){
    return view('master');
});
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');
These routes link to the corresponding methods in the ToastrController, allowing users to trigger success, error, info, and warning messages by visiting the respective URLs. This structure ensures a clean and organized way of handling user feedback throughout the application, making it easy to manage different types of notifications in one place.

Step # 6 : It's time to test.

Start the Laravel development server using the command.
php artisan serve
Access below URL in your browser and test the Toastr notifications.
127.0.0.1:8000

By clicking the button, a corresponding Toastr notification will appear based on the action you selected. Each button is configured to trigger a specific type of notification, such as success, error, info, or warning. This allows you to see real-time feedback in the form of a visually distinct message that matches the action you performed, providing clear and immediate communication to the user.

Conclusion

By following this guide, you’ve successfully integrated Toastr notifications into your Laravel application. This solution provides an effective way to display real-time feedback for users, enhancing their experience with clear success, error, info, and warning messages. The implementation is simple and can be easily customized to fit your application's needs. Whether you're improving user interaction or providing instant feedback, Toastr notifications are a great addition to any Laravel project.
For further information, refer to the official Toastr documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering