0
0
Laravelframework~5 mins

Creating jobs in Laravel

Choose your learning style9 modes available
Introduction

Jobs help you run tasks in the background so your app stays fast and responsive.

Sending emails without making users wait
Processing uploaded files like images or videos
Running slow database updates
Calling external APIs without blocking user actions
Scheduling tasks to run later or repeatedly
Syntax
Laravel
php artisan make:job JobName

// Inside the job class:
public function handle()
{
    // Task code here
}
Use php artisan make:job JobName to create a new job class.
The handle method contains the code that runs when the job is processed.
Examples
This job sends a welcome email to a user. It uses the ShouldQueue interface to run in the background.
Laravel
<?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
    }
}
This line adds the job to the queue to run later.
Laravel
SendWelcomeEmail::dispatch($email);
Sample Program

This example creates a job that logs a message. When dispatched, it prints the message to the console or log.

Laravel
<?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!');
OutputSuccess
Important Notes

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.

Summary

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.