Home > Backend Development > PHP Tutorial > Deferring Tasks in Laravel Using Queues

Deferring Tasks in Laravel Using Queues

William Shakespeare
Release: 2025-03-07 01:16:10
Original
547 people have browsed it

Deferring Tasks in Laravel Using Queues

This article explores Laravel's Queue API, a powerful tool for deferring computationally intensive tasks to improve user experience and website performance. We'll cover key concepts and illustrate them with a practical example.

Website speed significantly impacts SEO and user satisfaction. Slow page load times often stem from resource-heavy code blocks. The solution? Deferring non-critical tasks to improve overall speed. Laravel's Queue API provides a streamlined way to achieve this.

Laravel's Queue API manages jobs added to a queue. These queues are associated with connections, which in turn utilize specific queue drivers. Let's break down the components:

Queue Drivers

Similar to database connections, the Queue API supports various drivers, including database, beanstalkd, SQS, and Redis. The driver determines where queue information is stored (e.g., a database or Redis server). Two special drivers, null, are useful for testing; null skips job execution.

Connections

Queue configuration requires specifying a default connection. This connection defines:

  • The queue driver to use.
  • Driver-specific configuration settings.
  • The default queue name for new jobs.

Queues

Jobs are added to the default queue unless otherwise specified.

Now, let's build a real-world example: generating image thumbnails.

Creating Your First Queue Job

Generating multiple image thumbnails in real-time can negatively impact user experience, especially with large images or many thumbnail sizes. Instead of real-time processing, we'll defer this task to a queue. This approach offers a superior user experience as the main page loads quickly, and the thumbnail generation happens asynchronously.

Creating the Image Model

First, we'll create an Image model to manage uploaded images:

php artisan make:model Image --migration
Copy after login
Copy after login

This generates the Image model and a migration file. Modify the migration (database/migrations/YYYY_MM_DD_HHMMSS_create_images_table.php) to include the original image path:

<?php
// database/migrations/YYYY_MM_DD_HHMMSS_create_images_table.php
// ...
$table->string('org_path');
// ...
?>
Copy after login
Copy after login

Run the migration:

php artisan migrate
Copy after login
Copy after login

Creating a Laravel Job

We'll use the Intervention Image library for thumbnail processing. Install it via Composer:

php composer.phar require intervention/image
Copy after login

Create the job using the artisan command:

php artisan make:job ProcessImageThumbnails
Copy after login

Replace the contents of app/Jobs/ProcessImageThumbnails.php with:

<?php
// app/Jobs/ProcessImageThumbnails.php
// ...
public function handle()
{
    $image = $this->image;
    $full_image_path = public_path($image->org_path);
    $resized_image_path = public_path('thumbs' . DIRECTORY_SEPARATOR . $image->org_path);
    $img = \Image::make($full_image_path)->resize(300, 200);
    $img->save($resized_image_path);
}
// ...
?>
Copy after login

The handle method contains the thumbnail generation logic.

Testing the Job

Let's create a simple image upload form. Create a controller (app/Http/Controllers/ImageController.php):

php artisan make:model Image --migration
Copy after login
Copy after login

Create a view (resources/views/upload_form.blade.php) and add routes in routes/web.php:

<?php
// database/migrations/YYYY_MM_DD_HHMMSS_create_images_table.php
// ...
$table->string('org_path');
// ...
?>
Copy after login
Copy after login

The upload method handles file uploads, database entries, and dispatches the ProcessImageThumbnails job.

After uploading, verify the job's addition to the jobs table using a database query.

The Queue Worker

The queue worker processes queued jobs. Start it with:

php artisan migrate
Copy after login
Copy after login

This command processes pending jobs. The output will show job processing status. For continuous background processing, use a process manager like Supervisor, Circus, or similar.

Conclusion

Laravel's Queue API efficiently handles resource-intensive tasks, enhancing user experience. This article provided a foundational understanding and a practical implementation example. For further learning, explore resources at Envato Market.

The above is the detailed content of Deferring Tasks in Laravel Using Queues. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template