19 C
Jaipur
Wednesday, December 2, 2020

Laravel Queues Tutorial – Linux Hint

Must read

JD: JD.com, SF, Carlyle among bidders for CJ Group’s $1 billion China logistics business: Sources – Latest News

Chinese online retailer JD.com , delivery company SF Group and Carlyle are bidding for South Korean conglomerate CJ Group's China logistics business in a...

paytm: Paytm refutes report on China’s Ant Group considering stake sale – Latest News

Paytm on Wednesday refuted a report that said that one of the company's major shareholders, Chinese financial technology giant Ant Group, is considering the...

The Laravel queue is one of the more useful features of the Laravel framework. This feature is used to wait for time-consuming tasks and perform tasks at a later time to improve the performance and efficiency of the Laravel application. This feature provides different types of queues in back-ends, such as Amazon SQS, Redis, Beanstalk, synchronous driver, or relational database. A null queue driver is used to discard queued jobs. The configuration file of the queue is stored in the location config/queue.php. A common example of using the Laravel queue is to send emails. When it is required to deal with a large number of emails in the Laraval application, then it is better to use Laravel queues to speed up the processing. This tutorial shows how to use Laravel queues to send a large number of emails.

Prerequisites

Before beginning this tutorial, first, complete the following tasks:

  1. Install a fresh Laravel project
  2. Set up the database connection
  3. Set up the configuration for sending the emails (You can check the email sending tutorial to send email using SMTP)

Create Table

You must create the jobs table in the database to store all the queues. Run the following command from the terminal to create the migration file for the jobs table.

$ php artisan queue:table

You can open the migration file from the location database/migrations/. The file contains the following content.

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateJobsTable extends Migration
{
   /**
   * Run the migrations.
   *
   * @return void
   */

   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’);
      });
   }

   /**
   * Reverse the migrations.
   *
   * @return void
   */

   public function down()
   {
      Schema::dropIfExists(‘jobs’);
   }
}

Run the following command from the terminal to create the job table.

Create Mail Class

You must create a mailable class to send emails from the Laravel application. Run the following command to create the mail class named SendEmail in the location app/Mail.

$ php artisan make:mail SendEmail

The content of this class is shown below. The view filename that is used in the build() method will be created in the next part of this tutorial.

<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;

class SendEmail extends Mailable
{
     use Queueable, SerializesModels;

     /**
     * Create a new message instance.
     *
     * @return void
     */

     public function __construct()
     {
         //
     }

     /**
     * Build the message.
     *
     * @return $this
     */

     public function build()
     {
         /* Define the view name that will be used for email template */
         return $this->view(’email’);
     }
}

Create View

Create the view file named email.blade.php with the following content that will be sent as the email body.

<h3>Welcome to Linux Hint</h3>
<p>Learn Laravel easily</p>

Create a Job Class

Run the following command to create a job class. The job class filename named SendingEmail.php will be created in the location app/Jobs.

$ php artisan make:job SendingEmail

The content of the SendingEmail.php is shown below. You must set a valid email address inside the to() method of the handle() function to test whether the code is working properly. Set the valid email address in place of ‘Receiver Email Adress’ inside the to() method to check whether the queue is working properly.

<?php

namespace AppJobs;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;

/* Added the necessary packages */
use Mail;
use AppMailSendEmail;

class SendingEmail implements ShouldQueue
{
   use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

   /**
   * Create a new job instance.
   *
   * @return void
   */

   public function __construct()
   {
       //
   }

   /**
   * Execute the job.
   *
   * @return void
   */

   public function handle()
   {
       /* Create the object of mailable class and send email */
       $email = new SendEmail();
       /* Set a valid email address */
       Mail::to(‘Receiver Email Address ‘)->send($email);
   }
}

Create Controller

Run the following command to create a controller to handle the queue. When the handleQueue() function of the controller is executed, the queue job will be pushed and the email will send.

$ php artisan make:controller SendEmailController

SendEmailController.php

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;

/* Add the necessary packages */
use AppJobsSendingEmail;
use CarbonCarbon;

class SendEmailController extends Controller
{
   /**
   * Using Laravel Queues
   */

   public function handleQueue()
   {
    /* Push the new job in the job queue */
    dispatch(new SendingEmail());

    /* Print message after sending email */
    echo ‘Email has been Sent’;
   }
}

Add Route

Open the web.php file from the routes folder and add the following route to execute the queue job using the controller.

Route::get(’email’, [email protected]);

Run the following URL in the browser to check whether the code is working. Open the receiver email address to check whether a new email has been received.

http://localhost:8000/emailqueue

Add Delay

Open the SendingEmail.php file again and modify the content of the handleQueue() function to add the five-second delay to the queue jobs.

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;

/* Add the necessary packages */
use AppJobsSendingEmail;
use CarbonCarbon;

class SendEmailController extends Controller
{
   /**
   * Using Laravel Queues
   */

   public function handleQueue()
   {
    /* Create a new queue object with 5 seconds delay */
    $emailJob = (new SendingEmail())->delay(Carbon::now()->addSeconds(5));
    /* Push the new job in the job queue */
    dispatch($emailJob);
    /* Print message after sending email */
    echo ‘Email Sent after five seconds’;
   }
}

Again, run the following URL in the browser to check whether the code is working. Here, the email will be sent after five seconds, using the delay() method of five seconds.

http://localhost:8000/emailqueue

Check the inbox of the receiver email address to find out whether a new email has been received after 5 seconds. An email with the following content will be received if the queue job is working properly.

Conclusion

This tutorial shows very simple usage of the Laravel queue. You can use Laravel queues for various purposes, based on your application requirements. I hope that this tutorial has helped readers to better understand the basic concepts of Laravel queues.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

JD: JD.com, SF, Carlyle among bidders for CJ Group’s $1 billion China logistics business: Sources – Latest News

Chinese online retailer JD.com , delivery company SF Group and Carlyle are bidding for South Korean conglomerate CJ Group's China logistics business in a...

paytm: Paytm refutes report on China’s Ant Group considering stake sale – Latest News

Paytm on Wednesday refuted a report that said that one of the company's major shareholders, Chinese financial technology giant Ant Group, is considering the...