Sending Notification via Laravel Queue Example From Scratch

Hey Artisan,

In this tutorial, I will teach you how to send email notifications via queue in laravel 7. From this example, you will know how to send notifications in Laravel 7. 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 laravel queue, it makes a better experience. So let's start our tutorial by sending notifications in laravel 7 using laravel queue.

how-to-configure-laravel-queue

 

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. 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js