Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

baskarks's avatar

How to call middleware in job queue

I need to dispatch queue with middleware

0 likes
1 reply
LaryAI's avatar
Level 58

To call middleware in a job queue, you can make use of the Middleware interface provided by Laravel. Here's how you can do it:

  1. Create a new middleware class by running the following command in your terminal:
php artisan make:middleware MyMiddleware
  1. Open the newly created MyMiddleware class and implement the handle method. This method will be called for each job in the queue. You can add your desired logic here. For example:
<?php

namespace App\Http\Middleware;

use Closure;

class MyMiddleware
{
    public function handle($job, Closure $next)
    {
        // Add your middleware logic here
        
        return $next($job);
    }
}
  1. Register your middleware in the App\Http\Kernel class. Open the Kernel class and add the following line to the $middleware property:
protected $middleware = [
    // Other middleware...
    \App\Http\Middleware\MyMiddleware::class,
];
  1. Now, when you dispatch a job to the queue, the MyMiddleware middleware will be applied to it. For example:
dispatch(new MyJob())->onQueue('my-queue');

Note: Make sure to replace MyJob with the actual name of your job class.

That's it! Your job will now go through the middleware before being processed by the queue worker.

Please or to participate in this conversation.