Laravel 6 will add the ability to set middleware for specified queue tasks

  • 2021-12-19 06:03:16
  • OfStack

Taylor Otwell adds the ability to set up middleware for specified queued tasks in Laravel 6 so that we perform a bit of business logic before executing certain queued tasks:

This [pull request] adds an easy way to have specific middleware for queued jobs. Global job middleware were already possible by calling Bus:: pipeThrough ([]) in a a the application application provide provide a convenient provide EN some logic before they are executed.

We can define it in the Job class middleware() Method to set the corresponding middleware, which returns an array of middleware object instances, so multiple middleware can be defined:


public function middleware()
{
   return [new SomeMiddleware];
}

The following is a sample middleware code, which is not much different from the previous middleware definition, except that the $request parameter is replaced with $command :


class SomeMiddleware
{
  public function handle($command, $next)
  {
    // Do something...

    return $next($command);
  }
}

In addition, you can dynamically specify middleware when distributing tasks, which will be automatically and defined in the task class's middleware() Method returns the middleware merge:


SomeJob::dispatch()->through([new SomeMiddleware]);

This feature will be available in Laravel 6, which will be released at the end of this month. You can see more details in this Pull Request.

Summarize


Related articles: