Introduction
Jobs help you run tasks in the background so your app stays fast and responsive.
Jump into concepts and practice - no test required
Jobs help you run tasks in the background so your app stays fast and responsive.
php artisan make:job JobName
// Inside the job class:
public function handle()
{
// Task code here
}php artisan make:job JobName to create a new job class.handle method contains the code that runs when the job is processed.ShouldQueue interface to run in the background.<?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 $userEmail;
public function __construct($userEmail)
{
$this->userEmail = $userEmail;
}
public function handle()
{
// Code to send email to $this->userEmail
}
}SendWelcomeEmail::dispatch($email);
This example creates a job that logs a message. When dispatched, it prints the message to the console or log.
<?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 LogMessageJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected string $message; public function __construct(string $message) { $this->message = $message; } public function handle() { // Simulate logging by printing echo "Logging message: {$this->message}\n"; } } // Dispatch the job LogMessageJob::dispatch('Hello from the job!');
Jobs run asynchronously, so your app stays fast.
Make sure to configure your queue driver (like database or Redis) to process jobs.
You can dispatch jobs immediately or delay them for later.
Jobs let you run tasks in the background.
Create jobs with php artisan make:job and put code in handle().
Dispatch jobs to add them to the queue for processing.
php artisan make:job JobName.dispatch(new SendEmail()) is called?class SendEmail implements ShouldQueue {
public function handle() {
Mail::to('user@example.com')->send(new WelcomeMail());
}
}class ProcessData {
public function handle() {
// process data here
}
}php artisan make:job ProcessUploadhandle()ProcessUpload::dispatch()ShouldQueue interface if you want it queued