Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Run a Background Queue Job or Request in Laravel

How to Run a Background Queue Job or Request in Laravel ?

Aman Jain, May 17, 2022August 20, 2022

In any website running a queue can help to increase the runtime performance of any application by running a background queue job or request in laravel. Queues are much helpful while our application performs bulk actions like mailing to thousand of users or running a heavy tasks. In laravel we can optimize these tasks by utilizing the laravel queue services.

Laravel queue can increase the performance of the application by adding the scripts or task in order of come first, first serve. Some example of queues are sending email to user on first register or sending bulk newsletter mails.

When we use queue it sends all the task in background by putting the task in queue to process. In laravel we can configure queue in multiple ways like redis, database etc and then we can run artisan command to process the queue jobs one by one.

In this example we will send a mail in background so user won’t wait for the mail to send.

Let’s understand Run a Background Queue Job or Request in Laravel with step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

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

You can also read this to start with new project

Step 2: Configuration of Queue

As mentioned above laravel supports multiple drivers to support the queue so in this article i will use database driver to serve the queue so enable it in .env file first. Change the queue driver key to database and make database connection settings too as follow

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

QUEUE_CONNECTION=database

and mail settings also


MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=youremail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Now create queue migrations by running following command

php artisan queue:table

this will create migrations file in database migration folder as below

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

//in laravel 9
//return new class extends Migration

//and in below laravel 9
class Jobs 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');
    }
};

and now run artisan command to create tables of laravel queue

php artisan migrate

this will create below tables

laravel queue tables
laravel queue tables

Step 3: Create a mail class and template

In laravel 8 or 9 every mail is implements mailable class thus first we need to create a mail class as follow

php artisan make:mail QueueEmailTest

This will create a class in following location App\Mail\QueueEmailTest.php and update the below code

<?php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class QueueEmailTest extends Mailable
{
    use Queueable, SerializesModels;

    private $user;
    public function __construct($user)
    {
        $this->user=$user;
    }

    public function build()
    {
      return $this->from('from@gmail.com')
                    ->subject('Mail from readerstacks.com')
                    ->view('emails.test',["user"=>$this->user,"title"=>"Register"]);
    }
}

and Create a simple view for mail body in resources/views/emails/test.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Readerstacks.com</title>
</head>
<body>
    <h1>Hello {{ $user['name'] }}</h1>
    
    <p>{{ $user['body'] }}</p>
    <p>Simple mail using queue in background</p>
    
</body>
</html>

Step 4: Create a Job

Now create a job to handle our mail in background therefore create a job using following artisan command

php artisan make:job TestQueueSendEmail

Above command will create a file at location app\Jobs\TestQueueSendEmail.php and update the code as below

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\QueueEmailTest;
use Mail;

class TestQueueSendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

   
    public function handle()
    {
        $email = new QueueEmailTest($this->data);
        Mail::to($this->data['email'])->send($email);
    }
}

Step 5 : Create Route and Send Mail

Now, create a route and call dispatch method to call the queue class and add this mail to queue table using inline function as below

<?php

use Illuminate\Support\Facades\Route;
use App\Jobs\TestQueueSendEmail;

Route::get("/test-queue-mail",function(){

    $data=[
            'email' => 'info@readerstacks.com',
            "name"  => "Readerstacks",
            "body"  => "Simple mail from background"
            ];
  
    dispatch(new TestQueueSendEmail($data));
    return "You have just sent a mail in background";
});

Step 6 : Run queue worker in terminal

Final step is to run the queue worker so we can process the queue in background so run below command in terminal to watch the queue

php artisan queue:listen

Above method is useful while developing the application in local server since it will automatically reload the update code without manually stop and start but in production you need to run below command in supervisor

php artisan queue:work

To run above command continuously on server you need to install supervisor https://laravel.com/docs/9.x/queues#supervisor-configuration

Screenshot:

php artisan queue:listen
php artisan queue:listen

Related

Laravel Laravel 9 Php backgroundlaravelmailqueue

Post navigation

Previous post
Next post

Related Posts

Php get last insert id in laravel

How to get last insert id in laravel with example ?

March 5, 2022February 22, 2024

In this article i will learn you to get last insert id in laravel, In laravel we can execute our queries in two ways first is using the laravel eloquent and other one is DB builder. so in the both pattern we can get the last inserted i in laravel….

Read More
Php How to use left join in Laravel Eloquent

How to use left join in Laravel eloquent query with example

February 5, 2022February 8, 2024

In this article we will learn to use left join in laravel eloquent and query builder. Laravel itself provide inbuilt method to left join the table like in MySQL or SQL based database we can do join multiple tables using leftJoin function. For example if you have 10 rows and…

Read More
Php How to Use Bootstrap 5 in Laravel 9

How to Use Bootstrap 5 in Laravel 9 ?

May 30, 2022May 30, 2022

Bootstrap is a UI framework to enhance the beauty of website. In this tutorial i will show you to use Bootstrap 5 in laravel. Using the bootstrap we can enable multiple UI multiple functionality like we can show amazing buttons , card, input etc. Even with JavaScript library of bootstrap…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version