In my previous articles, I helped you create a Laravel email sending system and a Contact Us form.
In this article, I will highlight another amazing feature of Laravel through a very basic Laravel notification system. Using this system, I will send a notification to the user by sending them an email and integrate Slack to set up the system for sending notifications on a Slack channel.
Laravel’s notification system is easy to implement because 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.
Install Laravel
To quickly set up a Laravel application, sign up at Cloudways for free. Login to your account and create a new server. Fill in the server and the application details and select Laravel as your application. That’s it, you have just installed a functional Laravel application in just a few clicks on the Cloudways platform.
Create a User Table
Now that application has been installed, I will create a User table. Launch the SSH terminal and login to your server using the Master Credentials.
Now go to the root of your application by typing the following commands:
cd applications cd applicationname/public_html php artisan migrate
Now that you have a default User table in your database, the next step is the addition of a record in it so that the system could send a notification via email to that user. Go to the Applications tab on the Cloudways platform and launch the Database Manager.
Add a simple record in the table and add a valid email id in it. The system will send the notification to this 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', ]; }
If you look closely, you can see a Notifiable trait is been used. Whenever you want to make your model notifiable, all you have to do is to import use Illuminate\Notifications\Notifiable; a trait in your model.
Just note that certain notification channels expect 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.
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
For this example, I am keeping things very simple. A notification is generated whenever you get a visitor at the home page.
Go back to SSH, and in the root of your application, execute the following command:
php artisan make:notification Newvisit
By executing this command, you will have a Notification class. 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 [ // ]; } }
Let’s understand this code. First, it has the constructor, where any relevant data will be injected.
public function __construct()
Then, it has the via() method, which allows you to choose the notification method which will be used to send the notification to each instance.
public function via($notifiable) { return ['mail']; }
Then, it has toMail() method, which returns three attributes. The first one is the 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. Then 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!');
Related: Push Notification in PHP With OneSignal and Toastr
Send Email Notifications in Laravel
Now 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'); });
You would have to import notification class by 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(); then to send a notification, 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 [ // ]; } }
Next open .env file and set your database credentials and mailer function. Check out the Laravel Email article for details on this step. Your .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 [email protected] 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.
Create Slack Notifications in Laravel
To create a notification for Slack, you’ll need to bring Guzzle in via Composer. Go SSH and in the root of your application and run the following commands:
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
Now to receive Slack notification go to https://{yourteam}.slack.com/apps. Choose the “Incoming Webhook” type and add a new configuration.
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'; }
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:
Conclusion
In this tutorial, I created a Laravel notification system and how to send an email and Slack notifications in Laravel applications. If you have any query feel free to comment below and Subscribe to our blog for more Laravel tutorials.
Customer Review at
“Cloudways hosting has one of the best customer service and hosting speed”
Sanjit C [Website Developer]
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. You can email him at [email protected]