Job Middleware is Coming to Laravel 6

News

August 5th, 2019

laravel-6.png

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:

1public function middleware()
2{
3 return [new SomeMiddleware];
4}

And here’s an example of the middleware class:

1class SomeMiddleware
2{
3 public function handle($command, $next)
4 {
5 // Do something...
6
7 return $next($command);
8 }
9}

You can also specify middleware when dispatching a job:

1SomeJob::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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.