Laravel middleware. The most effective way

I am currently working with a laravel 5 project, which contains ~ 100 messages and receives routes. I am trying to add middlewares here, but the logic behind this project is really complex. Middlewares will play a really important role here. Before I used groups, for example:

Route::group(['middleware' => 'auth'], function(){ //routes }); 

But everything became very dirty, since I had to create groups in a group, for example:

  Route::group(['middleware' => 'auth'], function(){ Route::group(['middleware' => 'status'], function(){ //routes }); }); 

I currently have 20 controllers, so each of them contains about 5 routes. Could you offer me a more efficient way to use middlewares in large projects. Which way do you use? Thanks in advance!

+4
source share
1 answer

It all depends on what averages you should apply to different routes.

If you have route groups that use the same set of middleware, then the easiest way is what you do in the first example:

 Route::group(['middleware' => 'auth'], function(){ //routes }); 

If you have some roots that have common intermediaries, but each of them may have some specific middleware, then nested routes and route groups with an existing group, as in the second example, is the way:

 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 cannot group them in any way, you need to apply a set of intermediate elements to each of them:

  Route::get('/uri1/', ['middleware' => 'some_middleware']); Route::get('/uri2/', ['middleware' => 'some_other_middleware']); 

In short, if you have complex rules regarding which middleware applies to which routes, setting it up in the routes.php file will reflect complexity.

It may also be true that some of the things you do in the middleware should belong to a different layer in the application, and moving the logic can simplify routes.php , but it all depends on what routes and medium you have.
+1
source

All Articles