Get Appointment

Blog Single

Streamline Email Notifications with Laravel's Queue

  • Vfix Technology
  • 24 Dec 2023
  • Laravel
  • 143 Views

Introduction

In today's fast-paced digital world, effective communication is crucial for businesses to engage and retain users. Email notifications play a vital role in keeping users informed about important updates, events, and interactions within an application. However, sending email notifications synchronously can be a resource-intensive process, impacting the overall performance of your application. This is where Laravel's queue feature comes to the rescue, providing a seamless solution for efficient email notification handling.

Laravel, a popular PHP framework, offers a powerful notification system that simplifies the process of sending various types of notifications, including email notifications. By leveraging Laravel's built-in queue functionality, you can optimize the sending process, enhance efficiency, and improve user engagement. Let's explore how this works in detail.

To get started please follow the below steps here I am taking the simple example how you can send the notification on mail to your users when some post has been created on your website

Step:1 Install new laravel project

composer create-project laravel/laravel notificationQueue

Step: 2 Create notification

After you have completed the laravel installation. Create the notification by running following command

php atisan make:notification PostNotification

after running this command you will check that the new folder in app named notifications has been created which contain the file named PostNotification.

Step: 3 Create Controller

After the notification has been created create the controller named HomeController

php artisan create:controller HomeController

after creating the controller write the below code in it

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Notifications\PostNotification;
use Illuminate\Support\Facades\Notification;

class HomeController extends Controller
{
    public function index()
    {
        $users = User::get();

        $post = [
            'title' => 'post title',
            'slug'  => 'post-slug'
        ];

        foreach($users as $user){
            Notification::send($user, new PostNotification($post));
        }

        return view('welcome');
    }
}

Here I have taken the welcome page of laravel as my index page (I am expecting you know how to create route in laravel)

To work with notification I have imported the PostNotification and the facade of the Notification after this I have taken all the users from the and I am taking the post in an array formate and sending the notification on mail

Step: 3 Create smtp

After this to send email you have to create the smtp the use can use mailtrap for the testing of the mail over there you just create the account and then select the laravel 7+ you will get all smtp details over there and just pust the details in the .env file 

Step: 4 Write the code  in the PostNotification

After this  add this code

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class WelcomeNotification extends Notification implements ShouldQueue
{
    use Queueable;
    public $post;
    /**
     * Create a new notification instance.
     */
    public function __construct($post)
    {
        $this->post = $post;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    ->line($this->post['title'])
                    ->action('Notification Action', url('/' . $this->post['slug']))
                    ->line('Hello I am so glade to see on Welcome page!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            //
        ];
    }
}

Over here I have added the trait ShouldQueue  to send the notification instantly using queue than we have added the public variable $post and in construct function we have passed the variable after this in the toMail() function we have passed we have passed some lines and actions using the line() and action() function

public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
                ->line($this->post['title'])
                ->action('Notification Action', url('/' . $this->post['slug']))
                ->line('Hello I am so glade to see on Welcome page!');
}

Step: 5 Create the table for queue

To create the table for queue run the command 

php artisan queue:table

then run migration command

php artisan migrate

After this make some changes in env file 

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

In env file just search for the QUEUE_CONNECTION and make it database insted of sync because you are using database for the notification.

now start the sever and now if you will check the page is getting load faster then the previously. Now can check the jobs table in your database there will be a notification in queue the sened notification has beenn saved in the database temporarily.

Step: 6 Command to send the notifaction

After this process the notification is in queue to send it on mail we have to one a new cmd and we have to run the command 

php artisan queue:listen

this will send the notification on mail 

I hope you have understand all the process properly if you have any question just write it here

Official Documentation from laravel

Tags
Share :


+91 8447 525 204 Request Estimate