The Laravel 5 documentation describes two ways of assigning Middleware:
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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With