Search code examples
laravelroutesmiddleware

Laravel routes same url different controllers


In my Laravel application I have different roles (User, Manager, Admin).

I'd like to know the best practice to manage the home page for each of my users meaning I'd like to use the same url but different views.

It seems that it cannot be done directly in Routes:

Route::group(['middleware' => 'auth:user'], function () {
    $u = 'user.';
    Route::get('/', ['as' => $u . 'home', 'uses' => 'UserController@getHome']);
});

Route::group(['middleware' => 'auth:manager'], function () {
    $m = 'manager.';
    Route::get('/', ['as' => $m . 'home', 'uses' => 'ManagerController@getHome']);
});

Other way would be to redirect everyone to the same controller and inside the controller, display different views.

Route::group(['middleware' => 'auth:all'], function () {
        $a = 'authenticated.';
        Route::get('/', ['as' => $a . 'home', 'uses' => 'HomeController@getHome']);
    });

However it can become quite annoying if you have to manage more than 2 roles...

Last option would be to make some condition in the Routes like:

Route::group(['middleware' => 'auth:all'], function () {
            if (Auth::user()->hasRole('user)'{
            Route::get('/', ['as' => $a . 'home', 'uses' => 'UserController@getHome']);
    } else {
Route::get('/', ['as' => $a . 'home', 'uses' => 'ManagerController@getHome']);
}
        });

Many thanks


Solution

  • I wouldnt recommend the different view with different role in the route itself for me the best way would be creating the controller that handles the all frontpage request like for e.gFrontPageController.blade.php and return the view according the user and make sure u manage the view dir structure according to user role if the whole page seems different from one another like resources/views/product/admin/view

    resources/views/product/user/view
    resources/views/product/manager/view
    

    if the most the elements will be same for the template files i would recommend you to go for a gates