Laravel: Where to declare middleware?
Routes versus Controllers… fight!
While checking code from a coworker about a Laravel app, I saw that controllers constructors declared middleware, while routes also declared middleware. While this is normal on a Laravel application, some middleware were redundant.
After asking why, I received a weird answer: “I didn’t know which was was more appropriate, so I went for both”.
So, let’s have a clear purpose on why you should declare middleware on controllers, and when to use the routes.
When it makes sense on Controllers?
The prefered way to set middleware is on the controllers if the actions require a middleware to fully work. There are three clear advantages of this approach:
- It makes your routes declaration cleaner and easy to maintain.
- A middleware affects all the controller actions, nothing more.
- You can use
except()to selectively apply middleware on given routes.
For example, we should use our custom
admin middleware for a controller that handles banning management, like baning an user from the site. This middleware checks that only admins can enter to these actions.
On the other hand, if we have a middleware that changes the color of the site
When it makes sense on Routes
You should declare middleware on routes when the actions do not depend on the middleware.
For example, we have a middleware called
colorize, which applies a CSS style based on the post category. If we don’t declare it, all post will look the same, but doesn’t break the site in any way.
Not only we can assign it to only one route, but group multiple routes with the same middleware.
Let’s say, we want to apply the
colorize middleware to the posts and the comments section.
You may want to prioritize grouping multiple routes into a middleware to avoid repeating the same middleware over and over again in dozens of routes.
And that’s pretty much the reasoning behind it. Selectively using middleware for each route it can become very cumbersome over time, specially if you handle more than dozen or you plan to move routes.
Grouping routes with a common middleware can be a very good tool, even if you don’t prefix the grouped routes.