### Laravel: Specify job queue in the job's constructor Source: https://github.com/laravel/docs/blob/12.x/queues.md This alternative method demonstrates how to set a job's default queue by calling the `onQueue` method within the job's constructor. This approach is useful for consistently assigning a job to a specific queue whenever it is instantiated. ```php onQueue('processing'); } } ``` -------------------------------- ### Laravel: Dispatch a job to a specific connection and queue Source: https://github.com/laravel/docs/blob/12.x/queues.md This example demonstrates how to chain both `onConnection` and `onQueue` methods to dispatch a job to a particular queue on a specified connection. This allows for fine-grained control over job placement in complex queue setups. ```php ProcessPodcast::dispatch($podcast) ->onConnection('sqs') ->onQueue('processing'); ``` -------------------------------- ### Laravel: Dispatch a job to a specific queue using method chaining Source: https://github.com/laravel/docs/blob/12.x/queues.md This example shows how to dispatch a job to a particular named queue within a single queue connection. The `onQueue` method is chained after the job dispatch call to specify the target queue, such as 'processing'. ```php onQueue('processing'); return redirect('/podcasts'); } } ``` -------------------------------- ### Specify Connection and Queue for Laravel Job Batch Source: https://github.com/laravel/docs/blob/12.x/queues.md This example shows how to explicitly set the queue connection and specific queue for all jobs within a batch using the `onConnection` and `onQueue` methods. All jobs in a single batch must execute on the same connection and queue, ensuring consistent processing environments and resource utilization. ```php $batch = Bus::batch([ // ... ])->then(function (Batch $batch) { // All jobs completed successfully... })->onConnection('redis')->onQueue('imports')->dispatch(); ``` -------------------------------- ### Dispatching Laravel Jobs to Default and Specific Queues in PHP Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code demonstrates how to dispatch a job in Laravel, either to the default queue associated with the connection or to a specifically named queue, such as 'emails'. This allows for flexible job routing based on processing needs or priorities, ensuring jobs are handled by the appropriate workers. ```php use App\Jobs\ProcessPodcast; // This job is sent to the default connection's default queue... ProcessPodcast::dispatch(); // This job is sent to the default connection's "emails" queue... ProcessPodcast::dispatch()->onQueue('emails'); ``` -------------------------------- ### Laravel PHP: Dispatch a Job from a Controller Source: https://github.com/laravel/docs/blob/12.x/queues.md This code illustrates how to dispatch a job using the static `dispatch` method on the job class, typically from a controller. Arguments passed to `dispatch` are injected into the job's constructor. This immediately queues the job for processing by a worker. ```php onQueue('high')); ``` -------------------------------- ### Dispatch Job to Laravel Queue using PHP Source: https://github.com/laravel/docs/blob/12.x/helpers.md The `dispatch` function pushes a specified job instance onto the Laravel job queue for asynchronous processing. This allows long-running tasks to be executed in the background, improving application responsiveness. The function expects an instance of a job class as its argument. ```php dispatch(new App\Jobs\SendEmails); ``` -------------------------------- ### Process a Single Job with Laravel Queue Worker Source: https://github.com/laravel/docs/blob/12.x/queues.md Instructs the Laravel queue worker to process only one job from the queue and then exit. This is useful for testing or executing single, isolated jobs. ```shell php artisan queue:work --once ``` -------------------------------- ### Retry All Failed Jobs for a Specific Queue in Laravel Source: https://github.com/laravel/docs/blob/12.x/queues.md This Artisan command enables you to retry all failed jobs that belong to a particular queue. Specify the target queue's name using the `--queue` option to re-process only jobs from that queue. ```shell php artisan queue:retry --queue=name ``` -------------------------------- ### Fake All Laravel Jobs Except a Subset (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md Explains how to use `Queue::fake()->except()` to prevent all jobs from being pushed to the queue except for a specified list of job classes, which will be allowed to execute normally during testing. ```php Queue::fake()->except([ ShipOrder::class, ]); ``` -------------------------------- ### Specify Connection and Queue for Laravel Job Chain Source: https://github.com/laravel/docs/blob/12.x/queues.md This example illustrates how to define a specific queue connection and queue name for an entire job chain using the `onConnection` and `onQueue` methods. This allows for fine-grained control over where chained jobs are processed, overriding default settings for a particular sequence of tasks. ```php Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast, ])->onConnection('redis')->onQueue('podcasts')->dispatch(); ``` -------------------------------- ### Retry Multiple Failed Jobs by IDs in Laravel Source: https://github.com/laravel/docs/blob/12.x/queues.md To retry several failed jobs concurrently, provide multiple job IDs as arguments to this Artisan command. All specified jobs will be re-queued and processed sequentially or in parallel depending on your queue configuration. ```shell php artisan queue:retry ce7bb17c-cdd8-41f0-a8ec-7b4fef4e5ece 91401d2c-0784-4f43-824c-34f94a33c24d ``` -------------------------------- ### Laravel: Prepend or append jobs to an existing chain Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet demonstrates how to dynamically add new jobs to an existing job chain from within a currently executing job. It uses `prependToChain` to add a job immediately after the current one and `appendToChain` to add a job at the end of the chain. ```php /** * Execute the job. */ public function handle(): void { // ... // Prepend to the current chain, run job immediately after current job... $this->prependToChain(new TranscribePodcast); // Append to the current chain, run job at end of chain... $this->appendToChain(new TranscribePodcast); } ``` -------------------------------- ### Generate a new Laravel Job class using Artisan Source: https://github.com/laravel/docs/blob/12.x/queues.md This command creates a new job class file within the `app/Jobs` directory. The generated class automatically implements the `Illuminate\Contracts\Queue\ShouldQueue` interface, indicating it should be pushed onto the queue for asynchronous execution. ```shell php artisan make:job ProcessPodcast ``` -------------------------------- ### Dispatch Job Synchronously in Laravel using PHP Source: https://github.com/laravel/docs/blob/12.x/helpers.md The `dispatch_sync` function pushes the given job to the synchronous queue, causing it to be processed immediately in the current request cycle. This is useful for jobs that need to complete before the current request finishes. It bypasses the standard asynchronous queueing mechanism. ```php dispatch_sync(new App\Jobs\SendEmails); ``` -------------------------------- ### Laravel: Dispatch a job to a specific connection using method chaining Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet shows how to dispatch a job to a specific queue connection, such as 'sqs', using method chaining. The `onConnection` method is called after dispatching the job, allowing applications to interact with multiple queue connections. ```php onConnection('sqs'); return redirect('/podcasts'); } } ``` -------------------------------- ### Dispatch Initial Batch to Dynamically Add Jobs in Laravel Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code dispatches an initial batch of 'loader' jobs using `Bus::batch`. This pattern is useful for handling large numbers of jobs by first dispatching a smaller batch that will then add more jobs dynamically, preventing long web request times. ```php $batch = Bus::batch([ new LoadImportBatch, new LoadImportBatch, new LoadImportBatch, ])->then(function (Batch $batch) { // All jobs completed successfully... })->name('Import Contacts')->dispatch(); ``` -------------------------------- ### Laravel: Specify job connection in the job's constructor Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet shows an alternative way to set the default queue connection for a job by calling the `onConnection` method within its constructor. This ensures that the job is always dispatched to the specified connection when instantiated. ```php onConnection('sqs'); } } ``` -------------------------------- ### Start Laravel Queue Worker for Specific Connection and Queue Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts a Laravel queue worker that processes jobs only from a specific queue (e.g., 'emails') on a designated connection (e.g., 'redis'), allowing fine-grained control over job processing. ```shell php artisan queue:work redis --queue=emails ``` -------------------------------- ### Creating Laravel Jobs Table for Database Queue Driver using Artisan Shell Source: https://github.com/laravel/docs/blob/12.x/queues.md These shell commands are used to prepare the database for the Laravel database queue driver. The first command generates a migration file for the `jobs` table, and the second command runs pending migrations to create the table in the database, which is necessary to store queued jobs. ```shell php artisan make:queue-table php artisan migrate ``` -------------------------------- ### Run Queue Worker for Laravel Scout Jobs Source: https://github.com/laravel/docs/blob/12.x/scout.md If you customize the queue connection and queue that Scout jobs utilize, use this Artisan command to start a queue worker. This worker will process jobs specifically on the configured connection and queue for Scout. ```shell php artisan queue:work redis --queue=scout ``` -------------------------------- ### Delay Retrying Overlapping Laravel Jobs with PHP Source: https://github.com/laravel/docs/blob/12.x/queues.md This example shows how to configure the `WithoutOverlapping` middleware to release an overlapping job back to the queue after a specified number of seconds. This allows the job to be retried later, preventing immediate re-execution while still managing concurrency. ```php /** * Get the middleware the job should pass through. * * @return array */ public function middleware(): array { return [(new WithoutOverlapping($this->order->id))->releaseAfter(60)]; } ``` -------------------------------- ### Laravel PHP: Dispatch a Job with a Delay Source: https://github.com/laravel/docs/blob/12.x/queues.md This example shows how to dispatch a job with a specified delay using the `delay` method. The job will not be available for processing by a queue worker until the specified time has passed, here set to 10 minutes from now. This is useful for scheduling future tasks. ```php delay(now()->addMinutes(10)); return redirect('/podcasts'); } } ``` -------------------------------- ### Run Queue Worker with Backoff Delay (Shell) Source: https://github.com/laravel/docs/blob/12.x/queues.md This command starts a queue worker, similar to the previous one, but also introduces a backoff delay. The `--backoff=3` option instructs Laravel to wait 3 seconds before retrying a job that has encountered an exception, preventing immediate re-execution of a potentially problematic job. ```shell php artisan queue:work redis --tries=3 --backoff=3 ``` -------------------------------- ### Process All Queued Jobs and Exit with Laravel Queue Worker Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts a Laravel queue worker that processes all available jobs in the queue and then exits gracefully. This option is particularly useful when processing Laravel queues within a Docker container that should shut down after emptying the queue. ```shell php artisan queue:work --stop-when-empty ``` -------------------------------- ### Clear Jobs from Specific Laravel Horizon Queue (Shell) Source: https://github.com/laravel/docs/blob/12.x/horizon.md This shell command allows you to clear all jobs from a specific named queue within Laravel Horizon. By providing the `--queue` option with the queue's name, you can target and delete jobs only from that particular queue, such as an 'emails' queue. ```shell php artisan horizon:clear --queue=emails ``` -------------------------------- ### Add Jobs to Laravel Batch from within a Batched Job Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code, part of a `LoadImportBatch` job's `handle` method, demonstrates how to dynamically add more jobs to the current Laravel batch. It checks for cancellation and then uses the `batch()->add()` method to append a collection of new `ImportContacts` jobs. ```php use App\Jobs\ImportContacts; use Illuminate\Support\Collection; /** * Execute the job. */ public function handle(): void { if ($this->batch()->cancelled()) { return; } $this->batch()->add(Collection::times(1000, function () { return new ImportContacts; })); } ``` -------------------------------- ### Fake Laravel Queue and Assert Dispatched Jobs (Pest & PHPUnit) Source: https://github.com/laravel/docs/blob/12.x/queues.md Demonstrates how to prevent queued jobs from being pushed to the real queue using `Queue::fake()` and then assert various job dispatching behaviors such as `assertNothingPushed`, `assertPushedOn`, `assertPushed`, `assertNotPushed`, `assertClosurePushed`, `assertClosureNotPushed`, and `assertCount` in both Pest and PHPUnit testing frameworks. ```php dispatch(); ``` -------------------------------- ### Manually Release Laravel Job Immediately Source: https://github.com/laravel/docs/blob/12.x/queues.md Shows how to manually release a job back onto the queue for immediate reprocessing by calling the `release` method within the job's `handle` method. This allows the job to be attempted again. ```php /** * Execute the job. */ public function handle(): void { // ... $this->release(); } ``` -------------------------------- ### Force Laravel Queue Worker to Process Jobs During Maintenance Mode (Shell) Source: https://github.com/laravel/docs/blob/12.x/queues.md This command starts a Laravel queue worker that will continue to process jobs even when the application is in maintenance mode. It bypasses the default behavior of halting job processing during maintenance. ```shell php artisan queue:work --force ``` -------------------------------- ### Handle Laravel Failed Job Events in AppServiceProvider Source: https://github.com/laravel/docs/blob/12.x/queues.md Register an event listener for failed jobs using `Queue::failing()` within your Laravel `AppServiceProvider`'s `boot` method. This allows you to execute custom logic, such as logging or sending notifications, whenever a job fails, providing access to the connection name, job instance, and exception. ```php connectionName // $event->job // $event->exception }); } } ``` -------------------------------- ### Schedule Laravel Queued Job with Custom Queue and Connection Source: https://github.com/laravel/docs/blob/12.x/scheduling.md This example shows how to schedule a Laravel queued job while specifying a custom queue name and a custom queue connection as optional arguments to the `job` method. Here, the `Heartbeat` job is dispatched to the 'heartbeats' queue on the 'sqs' connection every five minutes. ```php use App\Jobs\Heartbeat; use Illuminate\Support\Facades\Schedule; // Dispatch the job to the "heartbeats" queue on the "sqs" connection... Schedule::job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes(); ``` -------------------------------- ### Laravel PHP: Dispatch Job Bypassing Default Delay Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet demonstrates the `withoutDelay` method, which allows a job to be dispatched for immediate processing, even if a default delay is configured for that job. This overrides any pre-set delays, ensuring the job enters the queue without waiting. ```php ProcessPodcast::dispatch($podcast)->withoutDelay(); ``` -------------------------------- ### Dispatch Laravel Job After Transaction Commit Inline Source: https://github.com/laravel/docs/blob/12.x/queues.md This code demonstrates how to explicitly instruct a job to wait for all open database transactions to commit before dispatching, even if the `after_commit` queue configuration is not set. By chaining the `afterCommit()` method onto the dispatch operation, the job will only be processed once the database changes are finalized. ```php use App\Jobs\ProcessPodcast; ProcessPodcast::dispatch($podcast)->afterCommit(); ``` -------------------------------- ### Define a Laravel Job class structure with constructor and handle method Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP example showcases the basic structure of a Laravel job class, including its constructor for dependency injection (e.g., an Eloquent model) and the `handle` method where the job's core logic is executed. The `Queueable` trait facilitates graceful serialization of Eloquent models. ```php withFakeQueueInteractions(); $job->handle(); $job->assertReleased(delay: 30); $job->assertDeleted(); $job->assertNotDeleted(); $job->assertFailed(); $job->assertFailedWith(CorruptedAudioException::class); $job->assertNotFailed(); ``` -------------------------------- ### Define a Batchable Laravel Job Class Source: https://github.com/laravel/docs/blob/12.x/queues.md To make a Laravel job batchable, the `Illuminate\Bus\Batchable` trait must be added to the job class. This trait provides access to the `batch()` method, allowing the job to retrieve information about the batch it belongs to, such as checking if the batch has been cancelled, enabling conditional execution logic within the job. ```php batch()->cancelled()) { // Determine if the batch has been cancelled... return; } // Import a portion of the CSV file... } } ``` -------------------------------- ### Apply Rate Limited Middleware to a Laravel Job Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP snippet shows how to attach the `RateLimited` middleware to a job's `middleware` method. By passing the name of a previously defined rate limiter ('backups'), the job will be subject to the specified rate limits. If the limit is exceeded, the middleware automatically releases the job back to the queue with an appropriate delay. ```php use Illuminate\Queue\Middleware\RateLimited; /** * Get the middleware the job should pass through. * * @return array */ public function middleware(): array { return [new RateLimited('backups')]; } ``` -------------------------------- ### Register Laravel Queue Job Lifecycle Callbacks (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code demonstrates how to register callbacks that execute before and after a queued job is processed using the `Queue` facade in Laravel. It's typically placed in the `boot` method of a service provider like `AppServiceProvider` and can be used for logging or updating statistics. The callbacks receive `JobProcessing` or `JobProcessed` event objects, providing access to job details. ```php connectionName // $event->job // $event->job->payload() }); Queue::after(function (JobProcessed $event) { // $event->connectionName // $event->job // $event->job->payload() }); } } ``` -------------------------------- ### Clear All Jobs from Default Laravel Horizon Queue (Shell) Source: https://github.com/laravel/docs/blob/12.x/horizon.md To remove all pending jobs from your application's default queue in Laravel Horizon, use the `horizon:clear` Artisan command. This shell command efficiently clears out the job queue, ensuring no jobs are processed from it. ```shell php artisan horizon:clear ``` -------------------------------- ### Asserting Laravel Job Chain Dispatch with Job Instances (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet shows an alternative way to assert a job chain dispatch using `Bus::assertChained`, providing actual job instances. Laravel will ensure that the dispatched jobs match the provided instances in class and property values. ```php Bus::assertChained([ new ShipOrder, new RecordShipment, new UpdateInventory, ]); ``` -------------------------------- ### Process a Fixed Number of Jobs with Laravel Queue Worker Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts a Laravel queue worker that processes a specified maximum number of jobs (e.g., 1000) before exiting. This helps in releasing accumulated memory, especially when combined with process monitors like Supervisor for automatic restarts. ```shell php artisan queue:work --max-jobs=1000 ``` -------------------------------- ### Define Job Batches in a Laravel Chain Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP example illustrates how to embed job batches within a Laravel job chain. It uses `Bus::chain` to specify a sequence of operations, where some steps involve processing multiple jobs concurrently within a `Bus::batch`. ```php use App\Jobs\FlushPodcastCache; use App\Jobs\ReleasePodcast; use App\Jobs\SendPodcastReleaseNotification; use Illuminate\Support\Facades\Bus; Bus::chain([ new FlushPodcastCache, Bus::batch([ new ReleasePodcast(1), new ReleasePodcast(2), ]), Bus::batch([ new SendPodcastReleaseNotification(1), new SendPodcastReleaseNotification(2), ]), ])->dispatch(); ``` -------------------------------- ### Configure Laravel Queue to Dispatch Jobs After Transaction Commit Source: https://github.com/laravel/docs/blob/12.x/queues.md This configuration snippet shows how to set the `after_commit` option to `true` within a queue connection's configuration. When enabled, Laravel will automatically wait for all open database transactions to commit before dispatching jobs, preventing issues where jobs might access uncommitted data. If no transactions are open, jobs are dispatched immediately. ```php 'redis' => [ 'driver' => 'redis', // ... 'after_commit' => true, ], ``` -------------------------------- ### Laravel PHP: Conditionally Dispatch Jobs Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet demonstrates `dispatchIf` and `dispatchUnless` methods for conditionally dispatching jobs. `dispatchIf` dispatches the job only if the first argument (condition) is `true`, while `dispatchUnless` dispatches if the condition is `false`. This provides a concise way to control job queuing based on application state. ```php ProcessPodcast::dispatchIf($accountActive, $podcast); ProcessPodcast::dispatchUnless($accountSuspended, $podcast); ``` -------------------------------- ### Generate Laravel Job Batching Migration and Run Migrations Source: https://github.com/laravel/docs/blob/12.x/queues.md This Artisan command creates a database migration file necessary to set up the table for storing meta-information about job batches, such as their completion percentage. After generation, the `migrate` command should be run to apply the changes to the database. ```shell php artisan make:queue-batches-table php artisan migrate ``` -------------------------------- ### Implement Basic Unique Job in Laravel Queue Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code demonstrates how to make a Laravel job unique by implementing the `ShouldBeUnique` interface. This ensures that only one instance of the `UpdateSearchIndex` job is processed at a time, preventing duplicate dispatches while an existing one is pending or processing. It requires a cache driver that supports atomic locks. ```php 0) { DB::rollBack(); } }); ``` -------------------------------- ### Fake Specific Laravel Queued Jobs (Pest & PHPUnit) Source: https://github.com/laravel/docs/blob/12.x/queues.md Shows how to fake only a subset of specific jobs by passing their class names to the `Queue::fake()` method, allowing other jobs to execute normally while still enabling assertions on the faked jobs in Pest and PHPUnit tests. ```php test('orders can be shipped', function () { Queue::fake([ ShipOrder::class, ]); // Perform order shipping... // Assert a job was pushed twice... Queue::assertPushed(ShipOrder::class, 2); }); ``` ```php public function test_orders_can_be_shipped(): void { Queue::fake([ ShipOrder::class, ]); // Perform order shipping... // Assert a job was pushed twice... Queue::assertPushed(ShipOrder::class, 2); } ``` -------------------------------- ### Asserting Laravel Job Has No Remaining Chain (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet shows how to use the job's `assertDoesntHaveChain` method to confirm that a job's remaining chain is empty, indicating no further jobs are expected in its sequence. ```php $job->assertDoesntHaveChain(); ``` -------------------------------- ### Asserting Laravel Job Batch Dispatch (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet uses `Bus::assertBatched` to verify that a batch of jobs was dispatched. The closure receives a `PendingBatch` instance, allowing for inspection of batch properties like name and job count. ```php use IlluminateBusPendingBatch; use IlluminateSupportFacadesBus; Bus::fake(); // ... Bus::assertBatched(function (PendingBatch $batch) { return $batch->name == 'Import CSV' && $batch->jobs->count() === 10; }); ``` -------------------------------- ### Start Laravel Queue Worker Source: https://github.com/laravel/docs/blob/12.x/queues.md This command starts a Laravel queue worker that continuously processes jobs. It runs until manually stopped, and changes in the codebase require a restart. ```shell php artisan queue:work ``` -------------------------------- ### Listen for Laravel QueueBusy Events to Send Notifications Source: https://github.com/laravel/docs/blob/12.x/queues.md Register an event listener for `Illuminate\Queue\Events\QueueBusy` within your Laravel `AppServiceProvider` to send notifications when a queue exceeds its configured job count threshold. This allows proactive alerts to a team, including details about the connection, queue, and current job size. ```php use App\Notifications\QueueHasLongWaitTime; use Illuminate\Queue\Events\QueueBusy; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Notification; /** * Bootstrap any application services. */ public function boot(): void { Event::listen(function (QueueBusy $event) { Notification::route('mail', 'dev@example.com') ->notify(new QueueHasLongWaitTime( $event->connection, $event->queue, $event->size )); }); } ``` -------------------------------- ### Retry Failed Laravel Batch Jobs Using Artisan Command Source: https://github.com/laravel/docs/blob/12.x/queues.md This shell command demonstrates how to retry all failed jobs within a specific batch. The `queue:retry-batch` Artisan command accepts the UUID of the batch whose failed jobs you wish to re-queue for execution. ```shell php artisan queue:retry-batch 32dbc76c-4f82-4749-b610-a639fe0099b5 ``` -------------------------------- ### Laravel PHP: Skip Job with Closure-based Conditional Middleware Source: https://github.com/laravel/docs/blob/12.x/queues.md This example shows how to pass a `Closure` to the `Skip::when` method for more complex conditional job skipping. The closure will be evaluated, and if it returns `true`, the job will be deleted. This provides flexibility for dynamic skip logic within the job's middleware. ```php use Illuminate\Queue\Middleware\Skip; /** * Get the middleware the job should pass through. */ public function middleware(): array { return [ Skip::when(function (): bool { return $this->shouldSkip(); }), ]; } ``` -------------------------------- ### Prevent Retries for Rate Limited Laravel Jobs Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP snippet shows how to prevent a job from being retried when it hits its rate limit using the `dontRelease` method on the `RateLimited` middleware. When `dontRelease` is used, the job will not be released back to the queue if it exceeds the rate limit, effectively failing at that point. ```php /** * Get the middleware the job should pass through. * * @return array */ public function middleware(): array { return [(new RateLimited('backups'))->dontRelease()]; } ``` -------------------------------- ### Define Parallel Job Chains in a Laravel Batch Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP code demonstrates how to execute multiple job chains in parallel within a Laravel batch. It uses `Bus::batch` to group chains, executing a callback function (`then`) once all jobs in both chains have completed successfully. ```php use App\Jobs\ReleasePodcast; use App\Jobs\SendPodcastReleaseNotification; use Illuminate\Bus\Batch; use Illuminate\Support\Facades\Bus; Bus::batch([ [ new ReleasePodcast(1), new SendPodcastReleaseNotification(1), ], [ new ReleasePodcast(2), new SendPodcastReleaseNotification(2), ], ])->then(function (Batch $batch) { // All jobs completed successfully... })->dispatch(); ``` -------------------------------- ### Process Jobs for a Fixed Duration with Laravel Queue Worker Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts a Laravel queue worker that processes jobs for a specified duration (e.g., 3600 seconds or 1 hour) before exiting. This helps in releasing accumulated memory, especially when combined with process monitors like Supervisor for automatic restarts. ```shell php artisan queue:work --max-time=3600 ``` -------------------------------- ### Chain Laravel Jobs Using Closures Source: https://github.com/laravel/docs/blob/12.x/queues.md This code demonstrates the flexibility of Laravel's job chaining by allowing closures to be included in the sequence. This enables inline execution of small, custom logic steps within a job chain, alongside standard job class instances, facilitating complex workflows. ```php Bus::chain([ new ProcessPodcast, new OptimizePodcast, function () { Podcast::update(/* ... */); }, ])->dispatch(); ``` -------------------------------- ### Start Laravel Queue Worker with Verbose Output Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts the Laravel queue worker with verbose output, displaying processed job IDs, connection names, and queue names for detailed monitoring. ```shell php artisan queue:work -v ``` -------------------------------- ### Dispatch a Batch of Laravel Jobs with Callbacks Source: https://github.com/laravel/docs/blob/12.x/queues.md This code dispatches a batch of `ImportCsv` jobs using the `Bus` facade. It defines various completion callbacks (`before`, `progress`, `then`, `catch`, `finally`) that execute at different stages of the batch's lifecycle, allowing for custom actions based on the batch's progress and outcome. The batch's ID is returned for later inspection. ```php use App\Jobs\ImportCsv; use Illuminate\Bus\Batch; use Illuminate\Support\Facades\Bus; use Throwable; $batch = Bus::batch([ new ImportCsv(1, 100), new ImportCsv(101, 200), new ImportCsv(201, 300), new ImportCsv(301, 400), new ImportCsv(401, 500), ])->before(function (Batch $batch) { // The batch has been created but no jobs have been added... })->progress(function (Batch $batch) { // A single job has completed successfully... })->then(function (Batch $batch) { // All jobs completed successfully... })->catch(function (Batch $batch, Throwable $e) { // First batch job failure detected... })->finally(function (Batch $batch) { // The batch has finished executing... })->dispatch(); return $batch->id; ``` -------------------------------- ### Start Laravel Queue Worker for Specific Connection Source: https://github.com/laravel/docs/blob/12.x/queues.md Starts a Laravel queue worker configured to process jobs from a specific queue connection, such as 'redis', as defined in your `config/queue.php` configuration file. ```shell php artisan queue:work redis ``` -------------------------------- ### Asserting Laravel Job Chain Dispatch with Class Names (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md This snippet demonstrates how to assert that a specific chain of jobs was dispatched using the `Bus::assertChained` method. It accepts an array of job class names to verify the sequence of dispatched jobs. ```php use AppJobsRecordShipment; use AppJobsShipOrder; use AppJobsUpdateInventory; use IlluminateSupportFacadesBus; Bus::fake(); // ... Bus::assertChained([ ShipOrder::class, RecordShipment::class, UpdateInventory::class ]); ``` -------------------------------- ### Manually Release Laravel Job with Delay Source: https://github.com/laravel/docs/blob/12.x/queues.md Illustrates how to manually release a job back onto the queue with a specified delay using the `release` method. The delay can be an integer representing seconds or a `DateTime` instance. ```php $this->release(10); $this->release(now()->addSeconds(10)); ``` -------------------------------- ### Set Laravel Queue Worker Max Attempts via Artisan Command Source: https://github.com/laravel/docs/blob/12.x/queues.md Configure the maximum number of times all jobs processed by a Laravel queue worker should be attempted using the `--tries` option on the `queue:work` Artisan command. This setting applies globally unless overridden by individual job definitions. ```shell php artisan queue:work --tries=3 ``` -------------------------------- ### Dispatch Laravel Job Before Transaction Commit Inline Source: https://github.com/laravel/docs/blob/12.x/queues.md This example illustrates how to force a specific job to be dispatched immediately, without waiting for any open database transactions to commit. This is useful when the `after_commit` configuration option is enabled globally, but a particular job needs to bypass that behavior and execute without delay. ```php ProcessPodcast::dispatch($podcast)->beforeCommit(); ``` -------------------------------- ### Asserting Laravel Job's Remaining Chain with assertHasChain (PHP) Source: https://github.com/laravel/docs/blob/12.x/queues.md When a chained job modifies the chain (prepends or appends jobs), this snippet demonstrates using the job's `assertHasChain` method to verify the expected sequence of remaining jobs in its chain. ```php $job = new ProcessPodcast; $job->handle(); $job->assertHasChain([ new TranscribePodcast, new OptimizePodcast, new ReleasePodcast, ]); ``` -------------------------------- ### Apply SkipIfBatchCancelled Middleware to a Laravel Job Source: https://github.com/laravel/docs/blob/12.x/queues.md This PHP example shows how to assign the `SkipIfBatchCancelled` middleware to a job. This middleware automatically prevents a job from being processed if its corresponding batch has already been cancelled, simplifying the job's logic by removing the need for manual checks. ```php use Illuminate\Queue\Middleware\SkipIfBatchCancelled; /** * Get the middleware the job should pass through. */ public function middleware(): array { return [new SkipIfBatchCancelled]; } ```