Laravel 8 Queue Step by Step Tutorial Example





This is a concise guide demonstrating a Laravel 8 queue example. This article presents a straightforward, step-by-step illustration of Laravel 8 queue implementation. Furthermore, I will showcase a Laravel 8 mail queue example, providing you with valuable insights into the process. Let's delve into the following steps.


Occasionally, certain processes such as sending emails or processing payment gateways can be time-consuming. When you send verification emails or invoices, there can be a delay due to the nature of these services. To eliminate the waiting time for users and expedite server-side processes, the implementation of a queue becomes highly beneficial. Not only does it enhance speed, but it also improves the overall user experience.


In this regard, I will share a straightforward example of creating a queue using the database driver for testing email sending. This example will provide a clear understanding of how queues function and highlight their ease of use. Even if you are new to this concept, there's no need to worry as the explanation starts from scratch and is exceptionally straightforward."


Step 1: Setup Laravel 8                                                  



First and foremost, we need to obtain the latest version of Laravel 8 application. To achieve this, kindly open your terminal or command prompt and execute the following command:


composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Mail Setup                                       


We are starting from scratch, and in the first step, we will create an email for testing purposes using the Laravel Mail facade. So, let's proceed by executing the following command:

php artisan make:mail SendEmailTest

Now you will have new folder "Mail" in app directory with SendEmailTest.php file. So let's simply copy bellow code and past on that file.


app/Mail/SendEmailTest.php


<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;  

class SendEmailTest extends Mailable

{

    use Queueable, SerializesModels;

    /**

     * Create a new message instance.

     *

     * @return void

     */

    public function __construct()

    {

    } 

    /**

     * Build the message.

     *

     * @return $this

     */

    public function build()

    {

        return $this->view('emails.test');

    }

}


Now, we need to create an email view using a Blade file. Let's proceed by creating a simple view file and copying the code provided below onto the designated path:


resources/views/emails/test.blade.php



<html>

<head>

    <title>How to send mail using queue in Laravel 8?</title>

</head>

<body>

   

Visit Our Website : v4techsolution.com

Hi, There

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamcasao laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

</body> </html>


After configuration of view file, we have to setup for email send, So let' set configuration in .env file:


.env

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=xyz@gmail.com

MAIL_PASSWORD=123456

MAIL_ENCRYPTION=tls

MAIL_FROM_ADDRESS=xyz@gmail.com

MAIL_FROM_NAME="${APP_NAME}" 
  

Step 3: Configuration of Queue                            


In the upcoming step, we will proceed with configuring the queue driver. To begin with, let's set the queue driver as "database." However, please note that you have the flexibility to choose any other desired driver, such as Redis. Now, let's define the database driver in the ".env" file:


.env

QUEUE_CONNECTION=database


After that we need to generate migration and create tables for queue. So let's run bellow command for queue database tables:


Generate Migration:

php artisan queue:table


Run Migration:

php artisan migrate

Step 3: Create Queue Job                          


Now, we will create a queue job by following the command. This command will generate a queue job file using Queueable. So, let's execute the command below:

php artisan make:job SendEmailJob

now you have SendEmailJob.php file in "Jobs" directory. So let's see that file and put bellow code on that file.



app/Jobs/SendEmailJob.php

 <?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Foundation\Bus\Dispatchable;

use Illuminate\Queue\InteractsWithQueue;

use Illuminate\Queue\SerializesModels;

use App\Mail\SendEmailTest;

use Mail;  

class SendEmailJob implements ShouldQueue

{

    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $details;  

    /**

     * Create a new job instance.

     *

     * @return void

     */

    public function __construct($details)

    {

        $this->details = $details;

    } 

    /**

     * Execute the job.

     *

     * @return void

     */

    public function handle()

    {

        $email = new SendEmailTest();

        Mail::to($this->details['email'])->send($email);

    }

}
 

Step 5: Test Queue Job                          


 let's simple create route with following code for testing created queue.

routes/web.php


  Route::get('email-test', function(){  

    $details['email'] = 'your_email_address@gmail.com';

    dispatch(new App\Jobs\SendEmailJob($details));

  

    dd('successful :)');

});
  

you can watch your queue process using laravel queue command, so let's run the below command.

php artisan queue:listen

You can also clear the config cache using below command:

php artisan config:clear


Now you can run the project using below command:

php artisan serve


 
If you have like this blog please add a comment I will create more blog regarding your requirements


Thank you :)

Comments