Jobs in Laravel are distinct pieces of work that can be run synchronously or queued for asynchronous processing. They are perfect for sending emails, resizing photos, processing file uploads, and communicating with external APIs.
Jobs are a core part of Laravel's queue system. It was designed to run background jobs and improve app performance by separating heavy tasks from the main app flow.
Create a job:
php artisan make:job SendEmail
In the job class:
namespace App\Jobs;
use Mail;
use App\Models\User;
class SendEmail implements ShouldQueue
{
public function __construct(public User $user) {}
public function handle()
{
Mail::to($this->user->email)->send(new WelcomeMail());
}
}
Dispatch the job:
SendEmail::dispatch($user);