DEV Community

Cover image for Creating a Laravel Notification System
Saquib Rizwan
Saquib Rizwan

Posted on

Creating a Laravel Notification System

An important reason of the popularity of Laravel is the simple fact that provides feasible solutions to the common development issues such as authentication, contact forms, sessions, queues, routing, and caching etc.

A common project requirement in Laravel projects is notification generation. In this article, I will present the solution by creating a Laravel notification system. In this system, whenever a user visits the page, a notification will be sent to you through email. To sweeten the deal, I will also integrate Slack to setup the notification for a Slack channel.

Laravel’s notification system is simple to implement because it generate notifications by setting up a single class for each notification. This class defines how to notify users about the message using a particular channel.

Install Laravel Application

To quickly setup a Laravel application, I am using Laravel Hosting at Cloudways. Just sign up at Cloudways and install Laravel application in just few clicks for free.

Host Laravel

Create a User Table

After the installation, create a User table. Launch the SSH terminal and login to your server using the Master Credentials (available in the Server Management tab)..

Laravel notification

Now go to the root of the application by typing the following commands:


cd applications

cd applicationname/public_html

php artisan migrate

Enter fullscreen mode Exit fullscreen mode

User table is now created in the database.

Now let's add some records into it so that the system can send notifications to that user. Go to the Database Manager and add a simple record in the table. Make sure to add a valid email id because the system will send the notification to this email address.

Laravel Notification

Now that the user model is created let’s take a look at it. Go to app/User.php that has the following code:


<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

   use Notifiable;

   protected $fillable = [

       'name', 'email', 'password',

   ];

   protected $hidden = [

       'password', 'remember_token',

   ];

}
Enter fullscreen mode Exit fullscreen mode

If you look closely, Notifiable trait is been used. Whenever you want to make your model notifiable, all you have to do is import use Illuminate\Notifications\Notifiable; trait in your model.

Just note that certain notification channels expects certain information available on the notifiable. For example, the mail channel expects the model to have an "email" property so it knows which email address to send the notification.

Notification Via Email

Go back to SSH, head to the root of your application and execute the following command:


php artisan make:notification Newvisit
Enter fullscreen mode Exit fullscreen mode

Now, go to app/Notifications/Newvisit.php. In this file you will find the following code:


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

class Newvisit extends Notification

{

   use Queueable;

   public function __construct()

   {

       //

   }

   public function via($notifiable)

   {

       return ['mail'];

   }

   public function toMail($notifiable)

   {

       return (new MailMessage)

                   ->line('The introduction to the notification.')

                   ->action('Notification Action', url('/'))

                   ->line('Thank you for using our application!');

   }

   public function toArray($notifiable)

   {

       return [

           //

       ];

   }

}
Enter fullscreen mode Exit fullscreen mode

Let’s understand this code. First, it has the constructor, where any relevant data will be injected.

public function via($notifiable)

   {

       return ['mail'];

   }
Enter fullscreen mode Exit fullscreen mode

Then, it has the via() method, which allows you to choose the notification method which will be used to send the notification to each individual instance.
Then, it has **toMail() **method, which returns three attributes. The first one is line, which specifies the starting body of the email. Then it has action, which specifies the button name and the URL to which the button will redirect. Finally, it has line again, which specifies the closing paragraph of the email. Here is a sample output:


       ->line('The introduction to the notification.')

       ->action('Notification Action', 'https://laravel.com')

       ->line('Thank you for using our application!');
Enter fullscreen mode Exit fullscreen mode

Laravel notification

Send Notifications Via Email in Laravel

Go to routes/web.php and paste the following code in the file:


<?php

use App\Notifications\Newvisit;

Route::get('/', function () {

$user = App\User::first();

$user->notify(new Newvisit("A new user has visited on your application."));

   return view('welcome');

});
Enter fullscreen mode Exit fullscreen mode

You would have to import notification class through use App\Notifications\Newvisit; then in the route function, I have called the first record from the User table which I inserted by** $user = App\User::first();. Next, the notification is sent for which I used the **notify function and send the notification in Newvisit instance in the following line of code: $user->notify(new Newvisit("A new user has visited on your application."));

Now open app\Notifications\Newvisit.php and add the following code in it.


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

class Newvisit extends Notification

{

   use Queueable;

   protected $my_notification; 

   public function __construct($msg)

   {

       $this->my_notification = $msg; 

   }

   public function via($notifiable)

   {

       return ['mail'];

   }

   public function toMail($notifiable)

   {

       return (new MailMessage)

                   ->line('Welcome '.$this->my_notification)

                   ->action('Welcome to Cloudways', url('www.cloudways.com'))

                   ->line('Thank you for using our application!');

   }

   public function toArray($notifiable)

   {

       return [

           //

       ];

   }

}
Enter fullscreen mode Exit fullscreen mode

Next open .env file and set the database credentials and mailer function. Check out the Laravel Email article for details of this step. The .env file should look like the following:


DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=zzjudekqvs

DB_USERNAME=zzjudekqvs

DB_PASSWORD=

BROADCAST_DRIVER=log

CACHE_DRIVER=file

SESSION_DRIVER=file

QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1

REDIS_PASSWORD=null

REDIS_PORT=6379

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=saquib.gt@gmail.com

MAIL_PASSWORD=

MAIL_ENCRYPTION=tls

PUSHER_APP_ID=

PUSHER_APP_KEY=

PUSHER_APP_SECRET=
Enter fullscreen mode Exit fullscreen mode

Now everything is ready. Go to the Application tab in the Cloudways platform and click the Launch Application button. You will be notified through an email.

Laravel Notification

Laravel notification

Send Notifications Via Slack in Laravel

To create and send notification for Slack, you’ll need to install Guzzle in via Composer. Launch SSH and in the root of the application, run the following commands:


composer require guzzlehttp/guzzle

php artisan make:notification Newslack
Enter fullscreen mode Exit fullscreen mode

You will need a new class for Slack notifications. For this, go to app/Notifications/Newslack.php and paste the following code.


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

use Illuminate\Notifications\Messages\SlackMessage;

class Newslack extends Notification

{

   use Queueable;

   public function __construct()

   {

       //

   }

   public function via($notifiable)

   {

       return ['slack'];

   }

   public function toSlack($notifiable)

   {

       return (new SlackMessage)

           ->content('A new visitor has visited to your application . $this->user->first(1->name)');

   } 

}
Enter fullscreen mode Exit fullscreen mode

Here, via() **method defines the medium for notification and **toSlack() method sends the notification onto Slack.

Set Incoming Webhook

Now to receive Slack notification, go to https://{yourteam}.slack.com/apps. Choose the "Incoming Webhook" type and add a new configuration.

Laravel notification

Copy the Webhook URL and head back to your Laravel app.

Your model should implement a routeNotificationForSlack() method that returns this webhook. Therefore go to app/User.php and add the following function in it.


public function routeNotificationForSlack()

   {

       Return 'your_webhook_url';

   }
Enter fullscreen mode Exit fullscreen mode

Now go to routes/web.php and add the following routes.


Route::get('/slack', function () {



$user = App\User::first();



$user->notify(new Newslack());



   echo "A slack notification has been send";



});
Enter fullscreen mode Exit fullscreen mode

Now go to the Application tab in the Cloudways platform, click the Launch Application button and add /slack in the url. You will receive Slack notification as shown below:

notification

Final Words

Laravel Notification system is a fascinating and very easy to implement feature that adds a lot of value to the project. You can use this example to create your own notification system that integrated into your Laravel app without any issues. If you need any help, you can comment below or DM me on twitter. Happy Coding.

Top comments (5)

Collapse
 
anmollohana profile image
anmollohana • Edited

A notification system is a great way to keep your users informed about your product's significant changes, announcements, and news. It can be used for anything from product updates to security alerts.
Thanks for sharing this informative piece of content. It will help many in performing the security tasks for their products.

Collapse
 
anonymouse703 profile image
anonymouse703

Hello sir, I've been stuck for almost a month about this problem.... I searched google and youtube but doesn't found an answer...

How to set Incoming webhook from github and make it as real time notification? I already installed guzzle and follow Laravel notification (which I got some hard to understand). when I hit the route and dd the data I receive the data that I want.. The problem is How to automatically hit the route sir?

Here is the thread I created in Laracast with no response yet.. laracasts.com/discuss/channels/lar...

Thank you and God bless.

Collapse
 
lebohash30 profile image
Lebo-hash30

Hello Sir
Thank you for sharing this good article. I have been struggling alot recently, trying to figure out how to send an email notification to a user; about his login credentials. Any assistance on that, I made use of YouTube as well nothing help.

Collapse
 
kabircse profile image
Kabir Hossain

Thanks for your nice article. Is it good or bad email verification using laravel notification ?

Collapse
 
adusoft profile image
Geofrey Aduda

I usually create my own customized email verification. I try as much to void the obvious framework email verification.