Failed job handling helps you know when a background task did not finish correctly. It lets you fix problems without losing data.
Failed job handling in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
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()); } }
Laravel
// Retry all failed jobs from the terminal
php artisan queue:retry allLaravel
// Delete all failed jobs from the terminal
php artisan queue:flushSample 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
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.
Practice
1. What is the primary purpose of the
failed() method in a Laravel job class?easy
Solution
Step 1: Understand the role of
Thefailed()methodfailed()method is a special method in Laravel job classes that runs when the job fails after all retry attempts.Step 2: Identify what
This method allows you to define custom logic like sending notifications or logging when a job fails.failed()doesFinal Answer:
To define actions when a queued job fails during execution -> Option CQuick Check:
failed()handles failure actions [OK]
Hint: Remember:
failed() runs only on job failure [OK]Common Mistakes:
- Confusing
failed()with retry commands - Thinking it lists or clears failed jobs
- Assuming it runs on successful job completion
2. Which of the following is the correct Artisan command to retry all failed jobs in Laravel?
easy
Solution
Step 1: Recall the syntax for retrying failed jobs
Laravel's command to retry failed jobs isphp artisan queue:retryfollowed by the job IDs orallto retry all.Step 2: Identify the correct option
The correct command to retry all failed jobs isphp artisan queue:retry all.Final Answer:
php artisan queue:retry all -> Option AQuick Check:
Retry all failed jobs =queue:retry all[OK]
Hint: Use 'all' after retry to retry every failed job [OK]
Common Mistakes:
- Adding extra flags like --all or --failed which don't exist
- Using incorrect command syntax
- Confusing retry with clear commands
3. Given this Laravel job class snippet, what will happen when the job fails?
class SendEmailJob implements ShouldQueue {
public function handle() {
// code that throws an exception
}
public function failed(Exception $exception) {
Log::error('Email sending failed: ' . $exception->getMessage());
}
}medium
Solution
Step 1: Analyze the
Thefailed()method implementationfailed()method logs an error message when the job fails due to an exception.Step 2: Understand job failure behavior
When the job throws an exception, Laravel callsfailed()and logs the failure message.Final Answer:
The job failure will be logged with the error message -> Option DQuick Check:
failed()logs failure message [OK]
Hint: Check if
failed() logs or retries [OK]Common Mistakes:
- Assuming job retries indefinitely without limit
- Thinking failure is ignored without logging
- Believing job succeeds despite exception
4. Consider this command to clear failed jobs:
php artisan queue:flushWhat is the issue with this command?
medium
Solution
Step 1: Verify the correct command to clear failed jobs
Thephp artisan queue:flushcommand does not exist in Laravel. The correct command to remove failed jobs isphp artisan queue:forget {id}for specific jobs or manually clearing thefailed_jobstable.Step 2: Confirm the issue
Sincequeue:flushis not a valid command, it cannot clear failed jobs.Final Answer:
The command does not exist; the correct command isqueue:forget-> Option BQuick Check:
queue:flushis invalid; usequeue:forget[OK]
Hint: Remember:
queue:flush is not a valid Artisan command [OK]Common Mistakes:
- Thinking
queue:flushdoes not exist - Confusing it with
queue:forgetfor specific jobs - Mistaking it for a retry command
5. You want to notify the admin by email whenever a job fails in Laravel. Which approach correctly implements this using the
failed() method?hard
Solution
Step 1: Understand how to handle job failure notifications
Laravel allows defining afailed()method in job classes to run custom logic on failure, such as sending emails.Step 2: Identify the correct implementation
Adding afailed()method that sends an email notification to the admin is the correct way to notify on failure.Final Answer:
Add afailed()method in the job class that sends an email notification to the admin -> Option AQuick Check:
Usefailed()to notify admin on job failure [OK]
Hint: Put notification code inside
failed() method [OK]Common Mistakes:
- Expecting Artisan commands to notify admin automatically
- Assuming database config sends emails
- Trying to set flags in constructor for notifications
