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 How to assign or declare variable in laravel blade template

How to assign or declare variable in laravel blade template ?

November 8, 2022March 16, 2024

Laravel blade is a powerful templating engine that gives you a lot of control over your HTML. One thing you can declare variable in laravel blade template easily by using different methds. This can be useful if you want to reuse a piece of data in your template, or if…

Read More

Create custom library or custom class in Laravel 8 / 9

December 21, 2021November 6, 2023

Laravel provides various packages and library to enhance our application features and functionalities but sometime we want our custom class in laravel to handle the few features of the application. Thus I this article i will show you to create a class and use it using the alias or directly…

Read More
Php How to Delete Cookies in Laravel

How to Delete Cookies in Laravel ?

July 26, 2022July 27, 2022

In this article we will learn to delete cookies in laravel. In our last article we learnt to set and get cookies and how cookies are used to store the data in client computer, Cookie can hold tiny information in computer and can retrieve when required for same website. In…

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

  • August 2025
  • July 2025
  • 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 Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version