Job Middleware is Coming to Laravel 6
Published on by Paul Redmond
Taylor Otwell added the ability to have job-specific middleware for queued jobs in Laravel 6:
This [pull request] adds an easy way to have job specific middleware for queued jobs. Global job middleware were actually already possible by calling
Bus::pipeThrough([])
in a service provider during the application boot process…These middleware provide a convenient location to wrap jobs in some logic before they are executed.
You define middleware by specifying a middleware()
method on the job class which returns an array of middleware objects. From the pull request, here’s an example:
public function middleware(){ return [new SomeMiddleware];}
And here’s an example of the middleware class:
class SomeMiddleware{ public function handle($command, $next) { // Do something... return $next($command); }}
You can also specify middleware when dispatching a job:
SomeJob::dispatch()->through([new SomeMiddleware]);
This feature will be a part of Laravel 6, due out later this month. Laravel v6 was announced at Laracon VII last month. It’s the next major release of Laravel due out sometime in August 2019.
To learn more about the code implementation for job-specific middleware, check out Pull Request #29391. The original idea surfaced from laravel/ideas #1356 if you want some background.