0
0
Laravelframework~30 mins

Creating jobs in Laravel - Try It Yourself

Choose your learning style9 modes available
Creating Jobs in Laravel
📖 Scenario: You are building a Laravel application that needs to send welcome emails to new users without slowing down the main app. You will create a job to handle sending the email asynchronously.
🎯 Goal: Build a Laravel job class called SendWelcomeEmail that accepts a User object and implements the handle method to send a welcome email.
📋 What You'll Learn
Create a job class named SendWelcomeEmail using the php artisan make:job command.
Add a public property $user to the job class to hold the user data.
Write a constructor that accepts a User object and assigns it to $user.
Implement the handle method to send a welcome email using Laravel's Mail facade.
💡 Why This Matters
🌍 Real World
Jobs help run time-consuming tasks like sending emails or processing files without slowing down the user experience.
💼 Career
Understanding Laravel jobs is essential for backend developers to build scalable and responsive web applications.
Progress0 / 4 steps
1
Create the job class
Create a job class named SendWelcomeEmail by running the artisan command php artisan make:job SendWelcomeEmail. Then, add a public property called $user to the class.
Laravel
Need a hint?

Use the artisan command to create the job class. Then add public $user; inside the class.

2
Add the constructor
Add a constructor method __construct to the SendWelcomeEmail class that accepts a User object as a parameter and assigns it to the $user property.
Laravel
Need a hint?

The constructor should accept $user and assign it to $this->user.

3
Implement the handle method
Add a handle method to the SendWelcomeEmail class. Inside it, use Laravel's Mail facade to send a welcome email to $this->user->email. Use a mailable class called WelcomeEmail and pass $this->user to it.
Laravel
Need a hint?

Use Mail::to($this->user->email)->send(new WelcomeEmail($this->user)); inside the handle method.

4
Dispatch the job
In your controller or wherever you want to send the welcome email, dispatch the SendWelcomeEmail job by passing the $user object. Use SendWelcomeEmail::dispatch($user); to queue the job.
Laravel
Need a hint?

Use SendWelcomeEmail::dispatch($user); to queue the job.