Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel grouping routes what is best prefix or middleware

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?

like image 952
Shahid Karimi Avatar asked Nov 28 '22 06:11

Shahid Karimi


2 Answers

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

like image 197
Luis felipe De jesus Munoz Avatar answered Dec 05 '22 22:12

Luis felipe De jesus Munoz


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');
});
like image 23
Naeem Ijaz Avatar answered Dec 05 '22 23:12

Naeem Ijaz