How to Create and Display Application Notification in Laravel 7

MacTavish
4 min readMay 10, 2020

Notifications are short and brief messages sent out to user of important actions and events in the app. Notifications improve User Experience by keeping them informed of the important events.

If you do not notify users, You may end up getting lot of support queries asking for information which a notification could have provided.

Enough Notification intro, let’s get to the How-to and code part.

For simplicity, we will send out notification to user upon registration.
Before anything else, We must build authentication feature. Laravel provides authentication out of the box. It’s a one min thing to make authentication system with Laravel.

You have to pull in Laravel Ui package which is responsible to build the entire authentication.

These two commands will generate the authentication system.

composer require laravel/ui

php artisan ui vue --auth

If you are starting a new app then you can use laravel new blog --auth to create a brand new app with authentication.

Next, you’ll have to compile some files with npm otherwise generated auth pages will have broken layout. Use the following command to compile files.

npm install && npm run dev

The next thing is Notifications. We will send out a notification when user will register. Each of your notification is represented by a Class.

Create Notification

Create a notification with the following command.

php artisan make:notification RegistrationSuccessful

The Four Steps

Before we build the Notification functionality, let’s consider the steps we have to perform.

1. The model which has to be notified should use “Notifiable” trait.

2. Your Notification class will contain code that will decided the content and appearance of notification.

3. Your notification must specify a delivery channel. We will use “mail” and “database”.

4. You have to decide when to send notification. In our case, we will send when a user registers.

Let’s do it step by step as outlined in Summary.

1. Your default user class already uses “Notifiable’ trait. If you want to notify some other model then add the following line inside your class body {}

use Notifiable;

2. Add the message to send in Mail Notification and Database notification. Replace the code in Notification class with below code.

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class RegistrationSuccessful extends Notification
{
use Queueable;

/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}

/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
// This will be sent in mail notification
return (new MailMessage)
->line("Congrats, You have successfully registered on another website. If you can't find login link then
please click on the big damn button we tailored for you!")
->action('Login Now', url('/login'))
->line('Thank you for using our application!');
}

public function toDatabase($notifiable) {
// This will be stored in Database, You'll fetch this notification later to display in application
return [
'body' => 'Yaay! You made it to here! You logged in to view the notification, SO damn Nice!',
];
}

}

3. Your notification delivery channel is specified in the “via” method of your Notification class. In our case we used the “mail” and “database channel”.

4. Let’s send the notification when User registers. Replace the “create” method of your “RegisterController” with following code.

protected function create(array $data)
{
$registered_user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
// New code to send the notification upon registration
$registered_user->notify(new RegistrationSuccessful());
return $registered_user;
}

Have been wondering what the heck is $notifiable ? It is the instance of the Class which will receive the Notification. In our case, It will be instance of User Class.

Since we are using Database channel, we will have to generate a migration and migrate the Database.

php artisan notifications:table

php artisan migrate

Above two commands will create a migration and migrate the database.

I am using Mailtrap for sending email. It’s very easy, just sign up and then you’ll to select “Laravel” from integration dropdown. This will generate some env variable for you which you will have replace with existing mail related variable in env file.

Lastly, Here is the moment of Result.

It’s time to show the Notification in Dashboard as well.

Display Notification

Go ahead and add the following code inside head tag of app.blade.php

// file layout/app.blade.php
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome-animation/0.2.1/font-awesome-animation.min.css" rel="stylesheet">

Replace the code in home.blade.php with below code.

home.blade.php

Finally replace the index function in HomeController.php with following code

// file app\Http\Controllers\HomeController.php
public function index()
{
$user = Auth::user();
return view('home')->with('notifications', $user->notifications);
}

Well done, You’re all good, it’s time to see your work in Action!

Notification Displayed to the User

Here is the GitHub Repository.

If you are looking for more info or want to go advanced, Read out the docs about Notifications.

--

--

MacTavish

Contributor in Tor Project, Web developer, Gamer. I tend to write article to help beginners.