Queues in Laravel are an excellent way to improve your application's performance by deferring the processing of time-consuming or resource-intensive tasks. In this tutorial, we'll explore how to use queues and jobs to send a welcome email to new users after they register
Step 1: Set Up the Database for Queues
First, we need to set up the database table for queues. Run the following commands:
php artisan queue:table
php artisan migrate
Step 2: Configure the Queue Driver
In the .env
file, set the queue driver to database:
QUEUE_CONNECTION=database
Step 3: Create a Job
Let's create a new job using the artisan command:
php artisan make:job SendWelcomeEmail
Step 4: Implement the Job
Open the app/Jobs/SendWelcomeEmail.php
file and implement the job:
<?php
namespace App\Jobs;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;
class SendWelcomeEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function handle()
{
Mail::to($this->user->email)->send(new WelcomeEmail($this->user));
}
}
Step 5: Create the Email Template
Create a new email class:
php artisan make:mail WelcomeEmail
Then implement it in app/Mail/WelcomeEmail.php
:
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class WelcomeEmail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function build()
{
return $this->view('emails.welcome')
->subject('Welcome to our site!');
}
}
Create the email template in resources/views/emails/welcome.blade.php
:
<h1>Welcome {{ $user->name }}!</h1>
<p>We're excited to have you on board.</p>
Step 6: Dispatch the Job to the Queue
Now, you can dispatch the job to the queue when a new user registers. For example, in app/Http/Controllers/Auth/RegisterController.php
:
use App\Jobs\SendWelcomeEmail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
SendWelcomeEmail::dispatch($user);
return $user;
}
Step 7: Run the Queue Worker
To process jobs in the queue, run the queue worker:
php artisan queue:work