Laravel 9 - How to Add Toastr Notifications

Laravel 9 - How to Add Toastr Notifications

Laravel 9 - How to Add Toastr Notifications

Hello Artisans, today I'll talk about implementing Toastr notifications in our Laravel application. Toastr is a JavaScript library that displays the message in the form of a notification. It can be a success, warning, info, or error. It is necessary when a user performs an action and we've to notify that user. So, let's see how we can use Toastr notifications in our application.


Note: Tested on Laravel 9.2.

  1. Install brian2694/laravel-toastr
  2. Add CSS and JS to html
  3. Create and Setup Controller
  4. Define Route
  5. Output

Install brian2694/laravel-toastr

Firstly we need to install the brian2694/laravel-toastr package. Run the below command in your terminal to install :

composer require brian2694/laravel-toastr

Add CSS and JS to html

Now we will modify the Laravel default welcome.blade.php. So, put the below code in yours.

resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel Toastr Notification</title>
        <link rel="stylesheet" href="http://cdn.bootcss.com/toastr.js/latest/css/toastr.min.css">
    </head>
    <body class="antialiased">
        <script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
        <script src="http://cdn.bootcss.com/toastr.js/latest/js/toastr.min.js"></script>
        {!! Toastr::message() !!}
    </body>
</html>

Create and Setup Controller


First we'll create a controller where we can use our logic to show user a toastr notification. Fire the below command in your terminal to create a controller.

php artisan make:controller ToastrNotificationController

Now put the below code in ToastrNotificationController.php.

app/Http/Controllers/ToastrNotificationController.php
<?php

namespace App\Http\Controllers;

use Brian2694\Toastr\Facades\Toastr;

class ToastrNotificationController extends Controller
{
    public function toastrNotification()
    {
        //put your logic here
        Toastr::success('You Have Successfully Implement Toastr Notification :)', 'Success!!');
        return view('welcome');
    }
}

Define Route

Now Replace your web.php file with the below codes.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
Route::get('toastr-notification',[\App\Http\Controllers\ToastrNotificationController::class,'toastrNotification']);

Output

Now if you go to http://127.0.0.1:8000/toastr-notification you'll see the below notification in the top right-most corner.

StarCode Kh

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

Previous Post Next Post
close