Back to Snippets
LaravelPHP

Laravel Job Queue

A queueable job for handling time-consuming tasks asynchronously.

laravelqueuejobasync
<?php

namespace App\Jobs;

use App\Mail\WelcomeEmail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

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

    public int 400">$tries = 3;
    public int 400">$backoff = 60;

    public function __construct(public User 400">$user) {}

    public function handle(): void
    {
        Mail::to(400">$this->user->email)->send(new WelcomeEmail(400">$this->user));
    }

    public function failed(\Throwable 400">$exception): void
    {
        logger()->error(class=class="text-emerald-400">"text-emerald-400">'Welcome email failed', [
            class=class="text-emerald-400">"text-emerald-400">'user' => 400">$this->user->id,
            class=class="text-emerald-400">"text-emerald-400">'error' => 400">$exception->getMessage(),
        ]);
    }
}

class=class="text-emerald-400">"text-gray">// Dispatch: SendWelcomeEmail::dispatch(400">$user);
class=class="text-emerald-400">"text-gray">// Delayed: SendWelcomeEmail::dispatch(400">$user)->delay(now()->addMinutes(5));

How to Use

Create with: php artisan make:job SendWelcomeEmail. Dispatch from controllers or events: SendWelcomeEmail::dispatch($user). Jobs run in the background via php artisan queue:work. Use tries and backoff for automatic retries.

Related Technology

Laravel

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call