At the moment I'm working with laravel 5 project, which contains ~100 post and get routes. I'm trying to add middlewares here but logics behind this project is really complicated. Middlewares will do really important role here. Before I was using groups, for example:
Route::group(['middleware' => 'auth'], function(){
//routes
});
But everything became really messy since I had to create groups in group, for example:
Route::group(['middleware' => 'auth'], function(){
Route::group(['middleware' => 'status'], function(){
//routes
});
});
At the moment I have 20 controllers, so each of them contains about 5 routes. Could you suggest me more efficent way to use middlewares in big projects. What way do you use? Thanks in advance!
It all depends on which middlewares you need to have applied to different routes.
If you have groups of routes that share the same middleware set, then the easiest way to do is what you do in the first example:
Route::group(['middleware' => 'auth'], function(){
//routes
});
If you have some roots that share common middlewares, but each of them might have some specific middleware applied, then nesting routes and route groups withing existing group like you do in the second example is a way to go:
Route::group(['middleware' => 'auth'], function(){
Route::group(['middleware' => 'status'], function(){
//routes
});
Route::get('/uri/', ['middleware' => 'some_other_middleware']);
});
Finally, when different routes have different middleware sets and you are not able to group them in any way, you'll need to apply a set of middlewares to each of them:
Route::get('/uri1/', ['middleware' => 'some_middleware']);
Route::get('/uri2/', ['middleware' => 'some_other_middleware']);
Long story short - if you have complex rules on what middleware to apply to what routes, then setting it up in the routes.php file will reflect the complexity.
It might be also true that some of the things you do in the middleware should belong to some other layer in the application and moving the logic there could simplify routes.php, but it all depends on what routes and middlewares you have.
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