Blogs / Programming

How to use Job Queues in Laravel 10 step-by-step tutorial

How to use Job Queues in Laravel 10 step-by-step tutorial

  • showkat ali
  • 0 Comments
  • 5188 View

In this article, we will see how to use the queue in Laravel 10. While developing your online application, you may come across operations that take too long to complete, such as parsing and storing an uploaded CSV file. Fortunately, queued tasks that can be completed in the background are simple to implement with Laravel. If your application assigns laborious tasks to a queue, it can respond to web requests faster and provide a better user experience to your clients.

Laravel Queues can help you improve the speed and responsiveness of your application by handling laborious tasks in the background. In this step-by-step tutorial, we will go over the fundamentals of Laravel Queues, including a comprehensive example and detailed explanations.

Step 1: Installation and Configuration

Install Laravel first, if you have not already. After installing Laravel, configure your database. Next, configure the queue connection in your .env file, specifying the desired driver (e.g., QUEUE_CONNECTION=database).

Step 2: Creating a Job

Jobs in Laravel represent tasks that can be executed asynchronously. Use the Artisan command to create a new job:

php artisan make:job ProcessTask
PHP

This creates a new job class in the App\Jobs directory. Open theProcessTask.php file and define your task logic within the handle method.

Step 3: Dispatching Jobs

Now, let us dispatch the job from your controller or wherever you need to start the background task. As an example:

use App\Jobs\ProcessTask;

public function someControllerMethod()
{
    ProcessTask::dispatch();
    
    return "Task dispatched successfully!";
}
PHP

Step 4: Configuring the Worker

Laravel includes a powerful worker system for handling queued jobs. Start the worker with the Artisan command:

php artisan queue:work
PHP

Step 3: Dispatching Jobs with Priority

Now, let's dispatch instances of the ProcessTask job with different priority queues. This is achieved using the onQueue method.

High-Priority Task:

ProcessTask::dispatch()->onQueue('high');
PHP

Explanation: In this example, we're dispatching theProcessTask job to a queue named 'high', indicating that this task has a high priority. Laravel allows you to create multiple queues, each with its own set of workers, enabling you to prioritize tasks based on their importance.

Real-world scenario: Assume you have critical tasks that require immediate attention, such as processing urgent user requests, sending time-sensitive notifications, or managing real-time updates. By moving these tasks to a high-priority queue, you ensure that they are completed quickly, resulting in a responsive and efficient system.

Default Priority Task:

ProcessTask::dispatch()->onQueue('default');
PHP

Explanation: This example dispatches the ProcessTask job to the default queue. The default queue typically processes tasks with a standard priority level. If no specific queue is mentioned, Laravel assumes the default queue.

Real-world scenario: For routine tasks that don't require immediate attention, like background data synchronization, periodic maintenance, or non-urgent notifications, the default queue is suitable. These tasks can be processed in the background without affecting the system's real-time responsiveness.

Low-Priority Task:

ProcessTask::dispatch()->onQueue('low');
PHP

Explanation: In this case, theProcessTask job is dispatched to a queue named 'low', indicating a low-priority task. Low-priority tasks are usually processed after higher-priority tasks, allowing you to manage system resources efficiently.

Real-world scenario: Imagine a scenario where you have resource-intensive tasks that can be deferred without impacting the immediate user experience, such as generating reports, batch processing, or non-critical background computations. Assigning these tasks to a low-priority queue ensures they are processed in a way that doesn't hinder the responsiveness of higher-priority operations.

 

For example, sending long-running emails asynchronously.

 

// 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 Mail;

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

    public $emailData;

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

    public function handle()
    {
        // Send the email using Mail facade or your preferred method
        Mail::send('emails.myEmail', $this->emailData, function ($message) {
            $message->to('recipient@example.com')->subject('My Email Subject');
        });
    }
}

// Usage in a controller
public function store(Request $request)
{
    // Validate and prepare email data
    $emailData = $request->all();

    // Dispatch the job to send the email asynchronously
    SendEmailJob::dispatch($emailData);

    return back()->with('success', 'Email sent successfully (queued)!');
}
PHP

Additional Considerations:

  • Prioritize Jobs: Laravel allows assigning different priorities to queues. Use theonQueue method before dispatching the job:
    MyJob::dispatch()->onQueue('high'); // Put the job in the 'high' priority queue
    PHP
  • Chaining Jobs: You can chain multiple jobs to execute one after another:
    MyJob1::dispatch()->chain(MyJob2::class, MyJob3::class);
    PHP
  • Error Handling: Implement proper error handling within the job class's handle method to handle exceptions and retry failed jobs if necessary.

 

  • Monitoring: Monitor the queue health using tools provided by your queue driver (e.g., Redis UI) or custom monitoring solutions.

 

In summary, Laravel's queue priority system enables you to strategically manage the execution order of tasks based on their importance and urgency, contributing to a more responsive and optimized application.

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance.

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

How to Use Quill Rich Text Editor Laravel 10: A Comprehensive Guide

How to Use Quill Rich Text Editor Laravel 10: A Comprehensive Guide

showkat ali
/
Programming

Read More
[FIXED]  target class [role] does not exist in  laravel 11

[FIXED] target class [role] does not exist in laravel 11

showkat ali
/
Programming

Read More
[ Fixed ] CSRF Token Mismatch in Laravel API

[ Fixed ] CSRF Token Mismatch in Laravel API

showkat ali
/
Programming

Read More
Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

showkat ali
/

Read More
How NVIDIA’s AI Technologies Can Accelerate Your Deep Learning, Data Science, and Edge AI Projects

How NVIDIA’s AI Technologies Can Accelerate Your Deep Learning, Data Science, and Edge AI Projects

showkat ali
/
Technology

Read More
Laravel 11 Pagination Guide - Complete Tutorial with Examples

Laravel 11 Pagination Guide - Complete Tutorial with Examples

showkat ali
/
Programming

Read More

We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Privacy Policy and Terms & Conditions.