Introduction
Dispatching jobs lets your app do tasks in the background. This keeps your app fast and smooth for users.
Jump into concepts and practice - no test required
Dispatching jobs lets your app do tasks in the background. This keeps your app fast and smooth for users.
JobClass::dispatch($parameters);
SendWelcomeEmail job to the queue with the user data.SendWelcomeEmail::dispatch($user);
ProcessVideo job but waits 10 minutes before running it.ProcessVideo::dispatch($video)->delay(now()->addMinutes(10));GenerateReport::dispatch();
This example shows a job class SendWelcomeEmail that takes a user and pretends to send an email by printing a message. Then it dispatches the job with a user email.
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SendWelcomeEmail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $user; public function __construct($user) { $this->user = $user; } public function handle() { // Imagine sending email here echo "Email sent to {$this->user['email']}\n"; } } // Dispatching the job $user = ['email' => 'friend@example.com']; SendWelcomeEmail::dispatch($user);
Make sure your queue worker is running to process dispatched jobs.
You can delay jobs to run later using the delay() method.
Jobs help keep your app responsive by moving slow tasks out of the main flow.
Dispatching jobs runs tasks in the background.
Use ::dispatch() on job classes to send jobs to the queue.
This improves app speed and user experience.
SendEmailJob in Laravel?::dispatch() on the job class to send it to the queue.SendEmailJob::dispatch(); uses SendEmailJob::dispatch(); which is the correct Laravel syntax.SendReportJob::dispatch(); return 'Report sent';
dispatch SendEmailJob();
::dispatch() on the job class, not by calling dispatch as a function.ProcessOrderJob with an order ID parameter 123. Which code correctly dispatches this job with the parameter?ProcessOrderJob::dispatch(123); calls ProcessOrderJob::dispatch(123); which passes 123 to the job constructor correctly.