This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Laravel Notification System On Slack And Email

Updated on July 14, 2023

7 Min Read
laravel-notification-system-on-slack

Previously, we created a Laravel email-sending system used by websites to send newsletters and collect feedback responses.

This blog highlights another Laravel feature, i.e., setting up a Laravel notification system on Slack and email. I will use this system to notify users via email and integrate Slack to send notifications on a Slack channel.

Laravel’s notification system notifies users via email or SMS. But there’s also a ” database ” driver that saves the messages within the application’s DB and shows them inside the framework as internal message alerts.

Moreover, Laravel’s notification system is easy to implement as it sends notifications by setting up a single class for each notification. This class describes how to notify users about the message using a particular channel.

What is the Difference Between Mailable and Notification in Laravel?

Mailable and Notification are both used to send messages to the user, but the former offers a flexible way to send emails and is more customizable than the latter. Notifications are useful when sending a predefined layout to different channels.

You can also customize the notification’s format; however, it is not recommended as you can only have one notification layout. What gives notifications an edge over Mailable is that it lets you notify users about the activities that happened on your site, like a user making a payment, closing an account, etc.

If you want to send the data via just one channel, such as email only, then it is ideal to use Mailable. But you should opt for notifications if you want to send information through multiple channels, like email, slack, SMS, etc.

How to Install Laravel on Cloudways (Quick Steps)

You can set up Laravel on Cloudways in a few minutes by following the steps below:

  • Sign up on the Cloudways Platform .
  • Log in to your account and create a new server .
  • Fill in the server and the application details and select Laravel as your application.
  • Click Launch Now and wait for a few minutes.

That’s how easily you can install a Laravel application with just a few clicks on Cloudways.

Cloudways Installation

Create a User Table

Now that you’ve installed Laravel, you need to create a User table.

Launch the SSH terminal and log in to your server using the Master Credentials.

server-credentials

Now access your application’s root folder by typing the following commands:

cd applications
cd applicationname/public_html

php artisan migrate

Follow the steps below once you have set up a default User table in your database:

  • Add a record so the system can send a notification via email to that user.
  • Go to the Applications tab on the Cloudways platform and launch the Database Manager.

laravel-slack
Add a record in the table and a valid email ID. The system will send notifications to the added email address.

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

   ];

}

You can see a Notifiable trait being used. So whenever you want to make your model notifiable, you must import and use Illuminate\Notifications\Notifiable; a trait in your model.

Note that some notification channels expect specific information available on the notifiable. For example, the mail channel expects the model to have an “email” property, so it knows the email address to send the notifications.

Improve Your Laravel App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

Create Notification For Email

The Laravel Notification feature lets you send users messages through various communication channels. Below is an example of how you can create a system where a notification is generated each time you have a visitor on the home page.

Go back to SSH in your application’s root, and execute the following command:

php artisan make:notification Newvisit

You will have a Notification class by executing this command. Go to app/Notifications/Newvisit.php, and 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 [

           //

       ];

   }

}

Let’s understand the code first.

The constructor is there to inject relevant data.

public function __construct()

Then, it has the via() method that lets you choose the method for sending notifications to each instance.

public function via($notifiable)

   {

       return ['mail'];

   }

You can also see the to Mail() method, which returns three attributes. The first is the line, which specifies the email’s starting body, followed by action, which specifies the button name and the URL to which the button will redirect. Finally, we have the line again, specifying the email’s closing paragraph.

 ->line('The introduction to the notification.')
       ->action('Notification Action', 'https://laravel.com')
       ->line('Thank you for using our application!');

email recieved

Related: Push Notification in PHP With OneSignal and Toastr

Send Email Notifications 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');

});

Import the notification class via use App\Notifications\Newvisit; then call the first record from the User table by inserting $user = App\User::first() to send a notification.

Use the notify function to send the notification in the 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 code below:

<?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 [
           //
       ];
   }
}

Open the .env file to set your database credentials and mailer function. You may refer to our Laravel Email blog for details on this step.

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
[email protected]
MAIL_PASSWORD=**************
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

Now, go to the Application tab on the Cloudways platform and click the Launch Application button.

You will get the notification via email.
cloudways-application-details

 

email received

Create Slack Notifications in Laravel

Add Guzzle via Composer to create a notification for Slack. Go to SSH and run the following commands in your application’s root:

composer require guzzlehttp/guzzle

php artisan make:notification Newslack

You will need a new class for Slack notifications. 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)');
   }


}

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

Set Incoming Webhook

Visit https://{yourteam}.slack.com/apps to receive Slack notifications. Choose Incoming Webhook and add a new configuration.

slack webhook

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

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

public function routeNotificationForSlack()
   {
       Return 'your_webhook_url';
   }

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";

});

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:

slack notification

Conclusion

Email notifications help increase your customers’ lifetime value and retention rates. So, you must ensure that your email notifications are high quality and work well.

In this tutorial, I created a Laravel notification system and demonstrated how to send email and Slack notifications in Laravel applications. If you have any queries feel free to comment below.

Q. What is the difference between mail and notification in Laravel ?

A: Laravel Mail or Mailable sends data via a single channel, like email. However, Notification lets you send information through multiple channels like email, slack, SMS, etc.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now