0
0
Laravelframework~5 mins

Dispatching jobs in Laravel

Choose your learning style9 modes available
Introduction

Dispatching jobs lets your app do tasks in the background. This keeps your app fast and smooth for users.

Sending emails without making users wait
Processing uploaded files like images or videos
Running slow database updates
Calling external APIs without delay
Generating reports or PDFs in the background
Syntax
Laravel
JobClass::dispatch($parameters);
Use the dispatch method on your job class to send it to the queue.
Jobs must implement the ShouldQueue interface to run in the background.
Examples
This sends the SendWelcomeEmail job to the queue with the user data.
Laravel
SendWelcomeEmail::dispatch($user);
This dispatches the ProcessVideo job but waits 10 minutes before running it.
Laravel
ProcessVideo::dispatch($video)->delay(now()->addMinutes(10));
This dispatches a job without any parameters.
Laravel
GenerateReport::dispatch();
Sample Program

This example shows a job class SendWelcomeEmail that takes a user and pretends to send an email by printing a message. Then it dispatches the job with a user email.

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;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function handle()
    {
        // Imagine sending email here
        echo "Email sent to {$this->user['email']}\n";
    }
}

// Dispatching the job
$user = ['email' => 'friend@example.com'];
SendWelcomeEmail::dispatch($user);
OutputSuccess
Important Notes

Make sure your queue worker is running to process dispatched jobs.

You can delay jobs to run later using the delay() method.

Jobs help keep your app responsive by moving slow tasks out of the main flow.

Summary

Dispatching jobs runs tasks in the background.

Use ::dispatch() on job classes to send jobs to the queue.

This improves app speed and user experience.