Creating a Laravel Notification System
Tags: laravel, webdev, php, tutorial
Published: 2017-11-09 12:08:50

---
title: Creating a Laravel Notification System
published: True
description: Learn How to create a Laravel Notification  
tags: Laravel,Webdev,PHP,tutorial 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/km70pecom0524qttto7z.jpeg
---

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](https://www.cloudways.com/en/laravel-hosting.php) at Cloudways. Just sign up at Cloudways and install Laravel application in just few clicks for free. 

![Host Laravel](http://www.cloudways.com/blog/wp-content/uploads/Laravel-Gif.gif)

## 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](https://thepracticaldev.s3.amazonaws.com/i/z977yi76358g72tk7ddw.png)

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

```php

cd applications

cd applicationname/public_html

php artisan migrate

```
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]
(https://thepracticaldev.s3.amazonaws.com/i/034ofh79i2zs4tobr897.png)

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

<?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',

   ];

}
```


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
```

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

```php

<?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 [

           //

       ];

   }

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

```php
public function via($notifiable)

   {

       return ['mail'];

   }
```

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:
```php

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

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

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

![Laravel notification](https://thepracticaldev.s3.amazonaws.com/i/8a7otaaspszdgp83uq0f.png)

## Send Notifications Via Email in Laravel  

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

<?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');

});
```

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

<?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 [

           //

       ];

   }

}
```
Next open **.env** file and set the database credentials and mailer function. Check out the [Laravel Email](https://www.cloudways.com/blog/send-email-in-laravel/) 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=
```

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](https://thepracticaldev.s3.amazonaws.com/i/9bkwmfdweodb3dpgdzlm.png)

![Laravel notification](https://thepracticaldev.s3.amazonaws.com/i/an4refcwpw0zrqptnqc7.png)

## 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
```

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

<?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)');

   } 

}
```
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](https://%7Byourteam%7D.slack.com/apps). Choose the "Incoming Webhook" type and add a new configuration.

![Laravel notification](https://thepracticaldev.s3.amazonaws.com/i/v9rqscubgigpn1u0618o.png)

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.
```php

public function routeNotificationForSlack()

   {

       Return 'your_webhook_url';

   }
```

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

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

 

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

 

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

 

   echo "A slack notification has been send";

 

});
```

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](https://thepracticaldev.s3.amazonaws.com/i/8upkhhc0alhq3cc86j0k.png)

## 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.