Laravel supports different queue drivers like database
, redis
, beanstalkd
, and sqs
.
Example: Set Queue Driver in .env
QUEUE_CONNECTION=database
Jobs define the logic for background tasks.
Example: Create a Job
php artisan make:job SendWelcomeEmail
app/Jobs/SendWelcomeEmail.php
.Modify the SendWelcomeEmail
Job (app/Jobs/SendWelcomeEmail.php
):
namespace App\Jobs;
use App\Mail\WelcomeEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendWelcomeEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
public function handle()
{
Mail::to($this->user->email)->send(new WelcomeEmail($this->user));
}
}
Dispatch the job when a new user registers.
Modify AuthController.php
:
use App\Jobs\SendWelcomeEmail;
public function register(Request $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
dispatch(new SendWelcomeEmail($user)); // Dispatch the job
return response()->json(['message' => 'User registered successfully']);
}
If using the database queue driver, create the jobs table.
Run the following commands:
php artisan queue:table
php artisan migrate
Start processing queued jobs using the worker.
Run the following command:
php artisan queue:work
If a job fails, you can retry or monitor it.
Example: Check Failed Jobs