Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Laravel middleware order of execution?

Tags:

The Laravel 5 documentation describes two ways of assigning Middleware:

  1. Assign middleware to the controller's route.
  2. Specify middleware within your controller's constructor.

However, I realised that any code written in the controllers __construct() function will run before the Middleware, even if the Middleware is declared on the first line of the controller's __construct function.

I found a bug report for a similar issue in the Laravel github repository. However a collaborator closed the issue stating "This is the expected behaviour.".

I am thinking that middleware should be "layers" outside the application, while the __construct function is part of the application.

Why is the __construct function executed before the middleware (given it is declared before middleware runs)? and why this is expected?

like image 327
Samuel Shen Avatar asked Jun 26 '15 05:06

Samuel Shen


People also ask

How can you assign middleware in Laravel?

Assigning Middleware To Routes If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel.

How does middleware work in Laravel?

Laravel Middleware acts as a bridge between a request and a reaction. It is a type of sifting component. Laravel incorporates a middleware that confirms whether or not the client of the application is verified. If the client is confirmed, it diverts to the home page otherwise, it diverts to the login page.

How do you call the middleware on a controller?

first, create middleware as your requirement, then you call middle using different method like: Route::get('admin/profile', ['middleware' => 'auth', function(){}]); or $this->middleware('auth'); in your controller __construct.

Can Laravel use two middleware?

To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once.


1 Answers

Another answer to cover another use case to that question

If it's related to the order between middleware it self

You can update the $middlewarePriority in your App\Kernel.

like image 58
Bdwey Avatar answered Oct 08 '22 13:10

Bdwey