Sometimes jobs in Laravel fail or need to be tried again. Job retries help automatically try a job again if it fails. Handling failures lets you manage what happens when retries stop.
Job retries and failure in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
class ExampleJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 5; // Number of retry attempts public $timeout = 120; // Max seconds before job times out public function handle() { // Job logic here } public function failed(Exception $exception) { // Logic when job fails after all retries } }
The $tries property sets how many times Laravel will retry the job before failing.
The failed() method runs only after all retries fail, letting you handle cleanup or notifications.
failed().class SendEmailJob implements ShouldQueue { public $tries = 3; public function handle() { // Send email logic } public function failed(Exception $exception) { // Notify admin about failure } }
failed() immediately on failure.class ProcessPaymentJob implements ShouldQueue { public $tries = 1; // No retries public function handle() { // Payment processing } public function failed(Exception $exception) { // Log failure } }
$tries = null means Laravel will keep retrying forever until success.class ImportDataJob implements ShouldQueue { public $tries = null; // Infinite retries (not recommended) public function handle() { // Data import } }
This example simulates a job that always fails. It tries 3 times, printing each attempt. After the last failure, it calls the failed() method to show the final failure message.
<?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; class ExampleJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; public function handle() { echo "Trying job...\n"; // Simulate failure throw new Exception("Job failed"); } public function failed(Exception $exception) { echo "Job failed after retries: " . $exception->getMessage() . "\n"; } } // Simulate running the job manually for demonstration $job = new ExampleJob(); for ($attempt = 1; $attempt <= $job->tries; $attempt++) { try { echo "Attempt $attempt:\n"; $job->handle(); break; // If success, stop retrying } catch (Exception $e) { echo "Caught exception: " . $e->getMessage() . "\n"; if ($attempt === $job->tries) { $job->failed($e); } } }
Time complexity: Job retries depend on external factors, but each retry runs the job logic once.
Space complexity: Minimal, mostly storing job data and retry count.
Common mistake: Forgetting to set $tries means Laravel uses default retries, which might be unexpected.
Use retries when failures are temporary. Use failed() to handle permanent failures like logging or alerts.
Set $tries in your job to control retry attempts.
Use the failed() method to handle what happens after all retries fail.
Retries help jobs recover from temporary problems without manual intervention.
Practice
$tries property in a job class control?Solution
Step 1: Understand the role of
The$triesin Laravel jobs$triesproperty defines how many times Laravel will attempt to run the job if it fails.Step 2: Differentiate from other job properties
It does not control execution time, priority, or database connection, only retry attempts.Final Answer:
The number of times the job will be retried if it fails -> Option AQuick Check:
$triescontrols retry attempts [OK]
- Confusing $tries with job timeout
- Thinking $tries sets job priority
- Assuming $tries controls database connection
Solution
Step 1: Recall the correct property name for retry attempts
Laravel uses$triesas a public property to set retry limits.Step 2: Check syntax and visibility
The property should be public and named exactly$triesto work properly.Final Answer:
public $tries = 5; -> Option AQuick Check:
Correct property ispublic $tries[OK]
- Using protected instead of public
- Using wrong property names like $retry or $triesCount
- Confusing retry limit with timeout
class SendEmailJob implements ShouldQueue {
public $tries = 3;
public function handle() {
// code that may fail
throw new \Exception('Failed');
}
public function failed() {
// handle failure
Log::info('Job failed permanently');
}
}How many times will Laravel attempt to run this job before calling
failed()?Solution
Step 1: Understand how
The$triesworks$triesproperty sets the maximum number of times the job will be attempted, including the initial attempt.Step 2: Calculate total attempts
With$tries = 3, Laravel attempts the job 3 times total before callingfailed().Final Answer:
3 times -> Option BQuick Check:
Total attempts =$tries= 3 [OK]
- Thinking total attempts = 1 + $tries
- Assuming retries are unlimited
- Confusing failed() call timing
class ProcessOrder implements ShouldQueue {
public $tries = 2;
public function handle() {
// some code
throw new \Exception('Error');
}
public function failed() {
// log failure
Log::error('Order processing failed');
}
}Why might the
failed() method never be called after job failures?Solution
Step 1: Check method signature for
Laravel expectsfailed()failed()to accept an Exception parameter to receive failure details.Step 2: Understand impact of missing parameter
Iffailed()lacks the Exception parameter, Laravel may not call it properly after retries.Final Answer:
Thefailed()method must accept an Exception parameter -> Option DQuick Check:
failed(Exception $exception)required [OK]
- Assuming $tries = 2 means infinite retries
- Forgetting to implement ShouldQueue interface
- Ignoring method signature requirements
Solution
Step 1: Use
Setting$triesto limit retry attemptspublic $tries = 3;ensures the job retries 3 times on failure.Step 2: Use
Definingfailed(Exception $exception)to handle final failurefailed()with the Exception parameter allows sending email after all retries fail.Final Answer:
Setpublic $tries = 3;and define afailed(Exception $exception)method to send the email notification -> Option CQuick Check:
Retries + failed() method for final failure handling [OK]
- Trying to send email inside handle() ignoring retries
- Using wrong property name like $maxAttempts
- Not using failed() method for final failure
