Cover Image for Notification message popup using toastr JS plugin in Laravel
232 views

Notification message popup using toastr JS plugin in Laravel

To integrate the Toastr JS plugin with Laravel’s notification system for displaying popup messages, follow these steps:

  1. Include Toastr JS: Start by including the Toastr JS library in your project. You can either download it and include it manually or use a content delivery network (CDN) link in your HTML layout.
PHP
 <!-- In your HTML layout -->
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
 <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
  1. Create a Notification Class: Create a Laravel notification class as discussed earlier. Customize the notification to include the JavaScript code needed to trigger the Toastr alert.
PHP
 // app/Notifications/ToastrNotification.php

 use Illuminate\Notifications\Notification;
 use Illuminate\Notifications\Messages\MailMessage;

 class ToastrNotification extends Notification
 {
     public function toToastr($notifiable)
     {
         return [
             'message' => 'This is your notification message.',
             'type' => 'success', // success, info, warning, error
         ];
     }
 }
  1. Trigger the Toastr Alert: In your notification class, use the toToastr method to customize the notification content and type. In your view or controller, you can use JavaScript to trigger the Toastr alert.
PHP
 // In your controller or view
 $user->notify(new ToastrNotification());
PHP
 <!-- In your JavaScript code -->
 <script>
     $(document).ready(function() {
         @foreach (Auth::user()->notifications as $notification)
             toastr.{{ $notification->data['type'] }}('{{ $notification->data['message'] }}');
         @endforeach
     });
 </script>

In this example, the JavaScript code loops through the notifications for the authenticated user and triggers Toastr alerts with the message and type specified in the notification.

  1. Customization: You can customize the appearance and behavior of Toastr notifications using the available options provided by the Toastr library. Refer to the official documentation for more details on configuration options: Toastr Documentation

Remember that the specifics of integration might have changed since my last update in September 2021, so always refer to the latest documentation for Toastr JS, Laravel, and any related libraries you’re using.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS