0
0
Laravelframework~5 mins

Failed job handling in Laravel

Choose your learning style9 modes available
Introduction

Failed job handling helps you know when a background task did not finish correctly. It lets you fix problems without losing data.

When a queued email fails to send and you want to retry later.
When processing a payment in the background fails and you need to log the error.
When importing large data files and some jobs fail, so you can review and retry.
When a notification job crashes and you want to keep track of it.
When you want to alert your team if any background task fails.
Syntax
Laravel
php
// To listen for failed jobs, define a failed() method in your job class
public function failed(Exception $exception)
{
    // Handle the failure, like logging or notifying
}

// To retry failed jobs from the command line:
php artisan queue:retry all

// To delete failed jobs:
php artisan queue:flush

The failed() method runs only if the job fails after all retries.

You can use php artisan queue:failed to list all failed jobs.

Examples
This example shows how to add a failed() method to log errors when the job fails.
Laravel
use Exception;
use Illuminate\Support\Facades\Log;

class SendEmailJob implements ShouldQueue
{
    public function handle()
    {
        // send email logic
    }

    public function failed(Exception $exception)
    {
        // Log the failure or notify admin
        Log::error('Email job failed: ' . $exception->getMessage());
    }
}
This command retries every job that failed before.
Laravel
// Retry all failed jobs from the terminal
php artisan queue:retry all
This command clears the list of failed jobs after you have handled them.
Laravel
// Delete all failed jobs from the terminal
php artisan queue:flush
Sample Program

This job tries to process an order. If the order ID is 0, it throws an error. The failed() method logs the failure message.

Laravel
<?php

namespace App\Jobs;

use Exception;
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\Log;

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

    public $orderId;

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

    public function handle()
    {
        // Simulate processing order
        if ($this->orderId === 0) {
            // Simulate failure
            throw new Exception('Invalid order ID');
        }
        // Process order logic here
        Log::info("Order {$this->orderId} processed successfully.");
    }

    public function failed(Exception $exception)
    {
        // Log failure details
        Log::error("Order {$this->orderId} failed: " . $exception->getMessage());
    }
}

// Usage example (not part of the job class):
// dispatch(new ProcessOrderJob(0)); // This will fail and trigger failed() method
OutputSuccess
Important Notes

Always add a failed() method to handle cleanup or notifications when jobs fail.

Use Laravel's built-in commands to manage failed jobs easily.

Check your queue driver supports failed job storage (like database or Redis).

Summary

Failed job handling helps catch and manage background task errors.

Use the failed() method in job classes to react to failures.

Laravel provides commands to list, retry, and clear failed jobs.