Add Toast Notification in Laravel 9

Hello devloper, Today we are going to learn how to add toast notification in laravel 9 application. This tutorial will cover on adding toast notification in laravel 9 application.

We are going to use Laravel Notify. Laravel Notify is a package that lets you add custom notifications to your project. A diverse range of notification design is available.

This tutorial is going to work in any version of laravel application laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9. Please let us know if any problem arise in any version.

You may also add toast notification into shopping website to show notification on successfully added to items to cart, remove from cart etc. There is a tutorial on how to add to cart in laravel you may want to check.

Also Read: Laravel 9 Shopping Cart Tutorial and Example

This tutorial Add Flexible Flash notifications for Laravel Application. So let get started with the tutorial.

Steps for Add Toast Notification in Laravel 9

  • Step 1: Install Laravel Application
  • Step 2: Configure Database
  • Step 3: Install Laravel Breeze
  • Step 4: Install Laravel Notify Package
  • Step 5: Add Laravel notify with laravel breeze
  • Step 6: Add Toast Notify In RegisteredUserController
  • Step 7: Testing

Step 1: Install Laravel Application

First we will going to install laravel application. You may also check laravel document on how to install laravel application. To install a laravel application into you system run the following command in terminal.

composer create-project --prefer-dist laravel/laravel laravel-add-toast

cd laravel-add-toast

This will install laravel application.

Step 2: Configure Database

Now, we need to connect the database with laravel application. We need the edit .env file and enter the database details.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-add-toast
DB_USERNAME=root
DB_PASSWORD=

Change the database details as per your database details.

Configure Database - Add Toast Notification
Configure Database – Add Toast Notification

Also Read: Laravel Add Watermark on Images

Step 3: Install Laravel Breeze

Its time to install a laravel breeze to our laravel application. Run the following command to install Laravel Breeze.

composer require laravel/breeze --dev
Install Laravel Breeze - Add Toast Notification
Install Laravel Breeze – Add Toast Notification

Now run the following command.

php artisan breeze:install
Breeze Install - Add Toast Notification
Breeze Install – Add Toast Notification
php artisan migrate
npm install
npm run dev
Breeze Install - Add Toast Notification
Database Migration – Add Toast Notification
Vite Running in Development - Add Toast Notification
Vite Running in Development – Add Toast Notification

Also Read: How to Check Date is Today’s Date or not in Laravel Carbon?

Step 4: Install Laravel Notify Package

Laravel Notify is a package that lets you add custom notifications to your project. A diverse range of notification design is available.

Install laravel notify package using composer. Run the following command to install notify package.

composer require mckenziearts/laravel-notify
Installing Laravel Notify - Add Toast Notification
Installing Laravel Notify – Add Toast Notification

You can publish the configuration file and assets by running:

php artisan vendor:publish --provider="Mckenziearts\Notify\LaravelNotifyServiceProvider"
Publish the configuration file for Laravel Notify
Publish the configuration file for Laravel Notify

Now that we have published a few new files to our application we need to reload them with the following command:

composer dump-autoload
Regenerate your package's autoload files
Regenerate your package’s autoload files

Now we are going to add laravel notify styles and scripts in our application. How to use Laravel styles and scripts and the functions to toasts messages.

  • Add styles links with @notifyCss
  • Add scripts links with @notifyJs
  • use notify() helper function inside your controller to set a toast notification for info, success, warning or error
  • Include notify partial to your master layout @include(‘notify::components.notify’)

Usage Example:

<!doctype html>
<html>
    <head>
        <title>Add Toast Notification in Laravel 9 - LaravelTuts.com</title>
        @notifyCss
    </head>
    <body>
        @include('notify::messages')
        <x:notify-messages />
        @notifyJs
    </body>
</html>

Also Read: How to Get All env Variables in Laravel?

Step 5: Add Laravel notify with laravel breeze

Now we are going to add laravel notify style and script to our laravel application to app.blade.php file:

resources/views/layouts/app.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">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Add Toast Notification in Laravel 9 - LaravelTuts.com</title>

        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap">

        <!-- Laravel Notify Style CSS -->
        @notifyCss

        <!-- Scripts -->
        @vite(['resources/css/app.css', 'resources/js/app.js'])
    </head>
    <body class="font-sans antialiased">
        <div class="min-h-screen bg-gray-100">
            @include('layouts.navigation')

            <!-- Page Heading -->
            @if (isset($header))
                <header class="bg-white shadow">
                    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                        {{ $header }}
                    </div>
                </header>
            @endif

            <!-- Page Content -->
            <main>
                {{ $slot }}
            </main>
        </div>
        <!-- Laravel Notify and Notify Script JS -->
        <x:notify-messages />
        @notifyJs
    </body>
</html>

Type of Notifications:

Laravel Notify actually display 5 types of notifications

  1. toast notification, (The default notification for Laravel Notify)
notify()->success('Welcome to Laravel Notify ⚡️') or notify()->success('Welcome to Laravel Notify ⚡️', 'My custom title')
  1. connectify notification, example of basic usage
connectify('success', 'Connection Found', 'Success Message Here')
  1. drakify (😎) notification, displays an alert only
drakify('success') // for success alert
or
drakify('error') // for error alert
  1. smilify notification, displays a simple custom toast notification using the smiley (😊) emoticon
smilify('success', 'You are successfully reconnected')
  1. emotify notification, displays a simple custom toast notification using a vector emoticon
emotify('success', 'You are awesome, your data was successfully created')

Also Read: Laravel Pagination Tutorial

Step 6: Add Toast Notify In RegisteredUserController

We are going to toast the message when user are register to our website to welcome them to our website.

app/Http/Controllers/Auth/RegisteredUserController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        Auth::login($user);

        //Toast Message when new user register
        notify()->success('Welcome to LaravelTuts.com⚡️');

        return redirect(RouteServiceProvider::HOME);
    }
}
Add Toast Notify In RegisteredUserController
Add Toast Notify In RegisteredUserController

Also Read: Laravel Carbon Time Format AM PM Example Code

Step 7: Testing

Now we had added the toast message to our laravel application when user register to our website. Its time to test our application. Run the following command in terminal to start the laravel server.

php artisan serve

also please keep running the vite also by the following command in new terminal

npm run dev

and open the following link in any web browser to test the application.

http://127.0.0.1:8000/

Now register of new user and test the toast message.

Previews:

Preview: Add Toast Notification in Laravel 9
Preview : Add Toast Notification in Laravel 9
Preview: Add Toast Notification in Laravel 9
Preview: Add Toast Notification in Laravel 9

Conclusion

Today, We had learn Add Toast Notification in Laravel 9. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel Change Mail Driver Dynamically Example

Leave a Reply