Toast Notification in Laravel 8 with Laravel Notify Package

Toast Notification in Laravel 8 with Laravel Notify Package

Admin
Admin・ 24 Agustus 2021
8 min read ・ 10879 views

Laravel Notification - The notification feature is a short message containing important information that is sent to the user. The Notification feature is indispensable for applications in the category of e-commerce, social media, blogs and others. Notification types are very diverse ranging from email notifications, whatsapp, sms, toast notifications (usually appear on website or application pages).

If we build an application or website using laravel as the framework, we can easily create notifications with broadcast media via email, sms, slack, whatsapp and toast notifications.

Laravel notify package

Now. In this article, we will try to explain and share a tutorial on how to easily create a toast notification in Laravel version 8. In this tutorial, we will create a toast notification using the laravel notify package from mckenziearts. Laravel notify is a package that allows us to add notification features in our projects. Laravel notify package has also provided a variety of attractive notification designs that we can use for free.

As an experiment, we will use or implement laravel notify to provide notifications to users who have successfully registered on our application or website. For that, in this experiment we will need the authentication feature and we will use the laravel ui package.

Okay, let's get straight to coding 🚀 👨‍🚀

Step 1: Install Laravel The Latest Version

laravel new laravel-notify

 

The first step we have to do, of course, starts with installing the latest version of laravel (currently version 8). There are several ways to install laravel, including the laravel installer with the command above and using composer with the command below.

composer create-project laravel/laravel laravel-notify

Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate a laravel project with the name laravel-notify.

Wait until the installation process is complete and when it's finished, don't forget to go to the project directory using the cd laravel-notify command.

Step 2: Install Laravel UI

composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev

Then, we need to install laravel ui package to create authentication feature in laravel. Run the commands as above sequentially. And if when you run the command npm install && npm run dev an error occurs, try running the command again.

Step 3: Setup Database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_notify
DB_USERNAME=root
DB_PASSWORD=

In the third step, we need to create a new database to hold the tables that will be used for data such as data users. Create a new database and don't forget to adjust the DB_DATABASE in the .env file like the example above.

php artisan migrate

And if you have finished creating a new database and setup the .env file, run the php artisan migrate command.

Step 4: Install Laravel Notify Package

composer require mckenziearts/laravel-notify

Then, we need to install laravel notify package into our laravel project. Run the command as above to install laravel notify.

php artisan vendor:publish --provider="Mckenziearts\Notify\LaravelNotifyServiceProvider"

 

Publish the config file and assets by running the command as above.

composer dump-autoload

Next, run the composer dump-autoload command as above.

Step 5: Setup Layout

<!doctype html>
<html>
    <head>
        <title>Laravel Notify</title>
        @notifyCss
    </head>
    <body>
        
        
        @include('notify::messages')
        // Laravel 7 or greater
        <x:notify-messages />
        @notifyJs
    </body>
</html>

In view, we just add styles links with @notifyCss, scripts links with @notifyJs and include notify partial to our master layout with @include('notify::messages') or for laravel version 7 and above can use <x:notify-messages />. For placing the scripts in the view, it can be seen as in the example above.

So, because we have used the laravel ui package which means we also have a master layout, namely app.blade.php which is located in the resources/views/layouts directory, then we need to add these three scripts in the app.blade.php file.

Step 6: Edit RegistersUsers.php

public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        if ($response = $this->registered($request, $user)) {
            return $response;
        }

        notify()->success('Hi '.$request->name.', welcome to codelapan');

        return $request->wantsJson()
                    ? new JsonResponse([], 201)
                    : redirect($this->redirectPath());
    }

Then open the RegistersUsers.php file which is located in the vendor/laravel/ui/auth-backend/RegistersUsers.php directory. In the register method, insert the script notify()->success('Hi '.$request->name.', welcome to codelapan');. With the addition of the script, when the user successfully registers, it will display a toast notification as on the cover of this article.

Laravel notify provides 5 types of notifications, namely:

  1. Toast notification (as implemented in the RegistersUsers.php file above)
    notify()->success('Welcome to Laravel Notify ⚡️')
    or
    notify()->success('Welcome to Laravel Notify ⚡️', 'My custom title')
  2. Connectify notification
    connectify('success', 'Connection Found', 'Success Message Here')
  3. Drakify notification (Display alert notification)
    drakify('success') // for success alert 
    or
    drakify('error') // for error alert 
  4. Smilify notification (display simple custom toast notification using smiley (😊) emoticon)
    smilify('success', 'You are successfully reconnected')
  5. Emotify notification (display simple custom toast notification using vector emoticon)
    emotify('success', 'You are awesome, your data was successfully created')

 

We can define preset notification in config file by using below structure.

'preset-messages' => [
    'user-updated' => [
        'message' => 'The user has been updated successfully.',
        'type'    => 'success',
        'model'   => 'connect',
        'title'   => 'User Updated',
    ],
    'user-deleted' => [
        'message' => 'The user has been deleted successfully.',
        'type'    => 'success',
        'model'   => 'connect',
        'title'   => 'User Deleted',
    ],
],

* The config file for laravel notify is located in the config folder with the name notify.php.

If we have a custom notification that is used in several different places on our system, we can define it as a preset notification in the config file. This can make it easier to keep commonly used notifications in one place.

notify()->preset('common-notification')

For example, to use a notification preset that has been defined with the name "common-notification", use a script like the example above.

notify()->preset('common-notification', ['title' => 'This is the overridden title'])

If needed, we can also change the value specified in the config file. For example, this notification can be useful for the general public, but we want to change the icon in one particular place that is used without having to write the notification manually. To do something like this, simply pass an array that has the key attribute we want to override and the value we want to override. For example, we can change the 'title' of 'common notification' by using a script like the one above.

Step 7: Testing

Okay, after going through the steps starting from installing the latest version of laravel (currently version 8), installing the laravel ui package, installing laravel notify package to the steps to setup blade view and RegistersUsers.php, then in this last step we will test whether toast the notification that we have created with laravel notify package is already working or not.

To test it, just run the laravel project first with the php artisan serve command, then open the browser by accessing the URL 127.0.0.1:8000/register or laravel-notification.test/register.

On the register page, please fill in the data in the available forms, then click register, then we will be directed to the Home page and a toast notification with the text "Hi yourname, welcome to codelapan" will also appear on the top right of the page.

Good luck, hopefully this article can be useful and see you in the next article.

Happy coding 🚀 🚀 🚀

 

Full Documentation: Laravel Notify

Tinggalkan Komentar
Loading Comments