Introduction
Background processing lets your app do slow tasks separately, so users don't wait. This makes your app feel faster and smoother.
Jump into concepts and practice - no test required
Background processing lets your app do slow tasks separately, so users don't wait. This makes your app feel faster and smoother.
dispatch(new JobClassName(parameters));
dispatch(new SendWelcomeEmail($user));
ProcessImage::dispatch($imagePath);
This example defines a job to send a welcome email in the background. When dispatched, it prints a message simulating the email sending without blocking the main app.
<?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; protected $user; public function __construct($user) { $this->user = $user; } public function handle() { // Simulate sending email echo "Sending welcome email to {$this->user->email}\n"; } } // Usage example $user = (object) ['email' => 'user@example.com']; dispatch(new SendWelcomeEmail($user));
Background jobs run separately from the main app, so users don't wait for slow tasks.
Always configure and run a queue worker to process jobs in the background.
Use queues to improve app responsiveness and user experience.
Background processing moves slow tasks away from user requests.
This makes apps faster and smoother for users.
Laravel provides easy tools to create and dispatch background jobs.
::dispatch() to send jobs to the queue for background processing.ProcessReport::dispatch(); uses correct syntax. dispatchNow(new ProcessReport()); runs job immediately, not in background. ProcessReport::run(); is invalid method. dispatchLater(ProcessReport); is not Laravel syntax.ProcessReport::dispatch(); -> Option AProcessReport::dispatch();
return response()->json(['status' => 'done']);
ProcessReport::dispatch() queues the job to run later, not blocking the current request.response()->json(), so user does not wait for the job.ProcessReport::dispatch;
ProcessReport::dispatch; without parentheses, so PHP treats it as a property, causing error.