Laravel 8 Send Notification Via Laravel Queue Example

Hey Artisan

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

It is better to use a queue in Laravel to send notifications. Because using of laravel queue, it makes your website faster. So let's start our tutorial by sending notifications in laravel 8 using laravel queue.

In this tutorial, we will learn from scratch that how to use a queue in laravel 8. 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 8 mail queue example.

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

 

Read also: Laravel Queue Example with Redis and Horizon

 

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 previous example.

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.

 

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 subscribers 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 provider

Illuminate\Notifications\NotificationServiceProvider::class

 

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

Step 3 : Setup Controller

Now paste the 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 the 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 [
            //
        ];
    }
}

 

Recommended: Laravel 8.x Queues Example with Redis and Horizon

 

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 table in the database. Run the 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 notifications to your subscriber via a queue. Hope it will work for you. Gives a thumbs up if you like this tutorial. 

 

#laravel #laravel-8x #laravel-queue