Laravel 7.x Send Notification via Laravel Queue Example

Hey Artisan

In this tutorial i am going to show you how send email notification via queue in laravel 7. Do you know how to send notification in Laravel 7? If you don't know, no problem. I will guide you step by step.

It is better to use queue in Laravel to send notification. Beacuse using of laravel queue, it make your website faster. So let's start our tutorial sending notification in laravel 7 using laravel queue.

In this tutorial we will learn from scratch that how to use queue in laravel 7. Send mail with queue in laravel gives us some benefit. Do you know what is this? If you don't know then follow this tutorial.  Let's see laravel 7 mail queue example.

In previous tutorial we have seen how to send notification in laravelIf you don't yet read this article then read this below article

Read: Laravel Notification Example From Scratch

But we know that it has some limitations. So now we will see how to send notification in laravel using queue. It is almost same just we have to change something in our code from prevoius example.

Why’ll you use Laravel Queue in our Application

Laravel queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer the processing of a time consuming task, such as sending an email, until a later time. Deferring these time consuming tasks drastically speeds up web requests to your application.

The queue configuration file is stored in config/queue.php In this file you will find connection configurations for each of the queue drivers that are included with the framework, which includes a database, BeanstalkdAmazon SQSRedis, and a synchronous driver that will execute jobs immediately (for local use). A null queue driver is also included which discards queued jobs.

how-to-configure-laravel-queue

Notification Example Via Laravel Queue

Now i am going to create a new post notification system in laravel using laravel queue. When we will create a new post then our all subscriber will be notified. Let’s see how we can do it.

 

Step 1: Creating Notification

In Laravel, each notification is represented by a single class (typically stored in the app/Notifications directory). Don't worry if you don't see this directory in your application, it will be created for you when you run the make:notification Artisan command:

php artisan make:notification NewPostNotify

 

This command will place a fresh notification class in your app/Notifications directory. Each notification class contains a via method and a variable number of message building methods(such as toMail or toDatabase) that convert the notification to a message optimized for that particular channel.

Step 2: Setup config/app.php

Now go to your config/app.php file and this providers

Illuminate\Notifications\NotificationServiceProvider::class

 

Now we have to setup our controller . So go to your controller and paste the following code

Step 3 : Setup Controller

Now paste this following code to your post controller.

app/Http/Controllers/PostController.php

namespace App\Http\Controllers\Admin;
 
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\user\Post;
use App\Notifications\NewPostNotify;
use Illuminate\Support\Facades\Notification;
use App\Model\user\Subscriber;
use Illuminate\Notifications\Notifiable;
 
class PostController extends Controller{
 
    public function store(Request $request)
    {
       //Save your new post here . after posting then send mail to the subscriber
 
        $subscribers = Subscriber::all(); //Retrieving all subscribers
 
        foreach($subscribers as $subscriber){
            Notification::route('mail' , $subscriber->email) //Sending mail to subscriber
                          ->notify(new NewPostNotify($posts)); //With new post
 
        return redirect()->back();
      }
    }
}

 

Step 4 :   Setup App/Notificatios/NewPostNotify.php

Now finally Setup your Notification file . Go you App/Notificatios/NewPostNotify.php file and paste those following code. Now here we have to change just one thing. Just add implements ShouldQueue after extends Notification

app/Notificatios/NewPostNotify.php

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

class Newpost extends Notification implements ShouldQueue
{
    use Queueable;
   
    public $post;
    public function __construct($post)
    {
       $this->post = $post;
    }
 
    public function via($notifiable)
    {
        return ['mail'];
    }
   
   public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('Hey, New article is availabe')
                    ->line('Higgs boson has published a new article')
                    ->line('Post title : '.$this->post->title) 
                    ->action('Read Post' , url(route('article' , $this->post->slug)))
                    ->line('Thank you for being with us!');
    }
   
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

 

Database Setup for Laravel Queues

In order to use the database queue driver, you will need a database table to hold the jobs. To generate a migration that creates this table, run the queue:table Artisan command. Once the migration has been created, you may migrate your database using the migrate command:

php artisan queue:table

You can use Redis . In order to use the redis queue driver, you should configure a Redis database connection in your config/database.php configuration file.

This command will create a migration file in the database/migrations folder. The newly created file will contain the schema for the jobs table which we need to process the queues.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateJobsTable extends Migration
{
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });
    }
 
 
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
}

 

Now it’s time to run the migrate command which will create the jobs table in database. Run below command to migrate:

php artisan migrate

Now we need to update the current queue drive in our environment file. Open your .envfile and change the queue drive to the database like below:

.env

QUEUE_DRIVER = database

All are almost done to configure laravel queue in our laravel app. Just run the below command to complete our queue setup.

php artisan queue:work

 

Read also : Laravel 7 Notification Tutorial | Create Notification with Laravel

 

If your mail server is ok then now you can send notification to your subscriber via queue. Hope it will work for you. Gives a thumbsup if you like this tutorial.