Send email notification in Laravel 5.6

Notification is one of my favorite feature in Laravel which was introduced in Laravel 5.3 and later. This feature allows sending notification events to the user. We can send notification through emails, SMS, and Slack. Also, notifications can be stored in our database that can be accessed later.

In this post, we will apply an email notification feature of Laravel. We will send a welcome message to the user through email notification. Let’s start coding!

Project Setup

Let’s install fresh Laravel:

Database
Create a database and configure .env file.

Email
For testing purpose, we will use mailtrap.io. If you are not familiar with this, just go to mailtrap.io and register your account. After registration, you will get username and password and configure .env file.

Auth scaffolding

Create Notification

As said earlier, we will send a welcome email to the user after registration. For this, we create a new notification with artisan command:

This will create a new file App/Notification/AccountCreated.php. If you dig into that file, you need to note two methods i.e. via and toMail method.

The via method is used to define channels the notification will be delivered like emails, SMS and Slack. The toMail method is used to send notification through email. Similar to this, you may add toDatabase.

Here we will add code to sends an email. So, our final code looks like below:

Configure User Model

To use notification, need to use Notifiable trait in User model.

App/User.php

Firing Notification
Now, it’s time to fire our notification. We will fire notification from RegisterController after user detail has been saved to the database. We can fire notification using notify method.

Since we will fire this notification after the user is created, we need to modify our create method only. Thus, our create method in RegisterController.php looks like below:

Optional: Queuing Notification

It is a good practice to add queue notification, it improves the application performance. we need to implement ShouldQueue interface and Queueable trait. For example:

Email Template

Laravel uses default email template notifications/emails.php. If you want to customize email template, you can publish email template and modify as per your requirements. To publish it, run the below artisan command:

This will publish your email.php template in resources/views/vendor/notifications/ directory. You can change this file and test.

All is done. Now email notification will be fired once user register to the application.

Leave a Reply

Your email address will not be published. Required fields are marked *