Laravel grouping routes what is best prefix or middleware
Solution 1
Wait. Prefix and middleware are two different things
prefix
is a way to Prefix your routes and avoid unnecessary typing e.g:
Route::get('post/all','Controller@post');
Route::get('post/user','Controller@post');
This can be grouped using prefix post
Route::group(['prefix' => 'post'], function(){
Route::get('all','Controller@post');
Route::get('user','Controller@post');
})
In the other hand, Middleware :
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
For example using last example now i want the users to be authenticated in my post routes. I can apply a middleware to this group like this:
Route::group(['prefix' => 'post', 'middleware' => ['auth']], function(){
Route::get('all','Controller@post');
Route::get('user','Controller@post');
})
You should check the docs to get more informed.
https://laravel.com/docs/5.5/middleware
https://laravel.com/docs/5.5/routing#route-groups
Solution 2
Both are different But to use both at the same time Best technique for grouping route middleware and prefix your route avoid unnecessary typing
Route::group(['prefix' => 'admin','middleware' => ['auth:admin']], function() {
Route::get('dashboard','AdminController@dashboard');
});
Shahid Karimi
Passionate, enthusiast IT professional in true spirit!
Updated on July 03, 2022Comments
-
Shahid Karimi almost 2 years
When I start thinking grouping my routes and check the documentation. I lost there. There are too many things like prefix, middleware etc.
What is the best way to group routes?
Route::group(['middleware' => 'admin'], function () {}); Route::group(['prefix' => 'admin'], function () {}); Route::group(['namespace' => 'admin'], function () {})
Which approach is best? And why? When to use what approach?
-
Luis felipe De jesus Munoz over 6 yearsIt is like a filter. before your request gets to the controller (or after, depends on the middleware type) the middleware handle the request and do things like validations, corrections, etc....
-
Shahid Karimi over 6 yearsCool, how to group all admin routes. Like admin/sales/report, admin/sales/report/edit/1 ???
-
Shahid Karimi over 6 yearsCool, how to group all admin routes. Like admin/sales/report, admin/sales/report/edit/1 ???
-
Luis felipe De jesus Munoz over 6 years
'prefix' => 'admin/sales/report'
and inside your routes