Using Laravel Queues & Jobs (Efficient Background Task Handling)

Using Laravel Queues & Jobs - Efficient Background Task Handling

1. Introduction to Laravel Queues & Jobs

Laravel Queues allow you to defer time-consuming tasks such as sending emails, processing large data, or API calls to improve application responsiveness.

2. Configuring Laravel Queues

Laravel supports multiple queue drivers like database, Redis, and Amazon SQS. To configure queues, update the .env file:

QUEUE_CONNECTION=database

3. Setting Up Database Queue

Run migrations to create the queue table:

php artisan queue:table
php artisan migrate

4. Creating a Job

Generate a job using Artisan:

php artisan make:job SendEmailJob

Update app/Jobs/SendEmailJob.php to process the email:

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;

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

    public function handle() {
        Mail::to($this->user->email)->send(new WelcomeMail($this->user));
    }
}

5. Dispatching the Job

To dispatch the job, use:

SendEmailJob::dispatch($user);

6. Running the Queue Worker

Start the queue worker to process jobs:

php artisan queue:work

7. Supervising Queue Workers

Use Supervisor to keep queue workers running in production:

sudo apt install supervisor

Configure /etc/supervisor/conf.d/laravel-worker.conf:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path-to-your-project/artisan queue:work
autostart=true
autorestart=true
numprocs=1
redirect_stderr=true
stdout_logfile=/path-to-your-project/storage/logs/worker.log

8. Conclusion

Using Laravel Queues and Jobs enhances application performance by handling background tasks efficiently. Implement queue workers to optimize task execution.

Published by Developer Sahayak - Helping Developers Solve PHP, Laravel, and Drupal Issues.

0 Comments