Laravel 5 Entrust one route - load different controller based on Role

后端 未结 1 1192
耶瑟儿~
耶瑟儿~ 2021-01-16 16:45

So I\'m just starting to learn Laravel and I\'ve implemented the Entrust Role Permission package, which works really well. Now my question is, I\'d like to have a \'Dashboar

相关标签:
1条回答
  • 2021-01-16 17:36

    Something like this should work for you.

    routes.php

    Route::get('/dashboard', ['as'=>'dashboard', 'uses'=> 'DashboardController@dashboard']);
    

    DashboardController.php

    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    
    use App\User;
    use App\Admin;
    
    class DashboardController extends Controller {
        public function dashboard(){
            if ($this->auth->user()->hasRole('admin') )
            {
                return $this->showAdminDashboard();
            }
            elseif ($this->auth->user()->hasRole('user') )
            {
                return $this->showUserDashboard();
            }
            else {
                abort(403);
            }
        }
    
        private function showUserDashboard()
        {
            return view('dashboard.user');
        }
    
        private function showAdminDashboard()
        {
            return view('dashboard.admin');
        }
    }
    

    Edits per comment

    It sounds like something like this approach might be what you are looking for.

    <?php
    
    $uses = 'PagesController@notfound';
    if( $this->auth->user()->hasRole('admin') )
    {
        $uses = 'AdminController@index';
    }
    elseif ($this->auth->user()->hasRole('user') )
    {
        $uses = 'UsersController@index';
    }
    
    
    Route::get('/dashboard', array(
         'as'=>'home'
        ,'uses'=> $uses
    ));
    

    That said, I feel like having a DashboardController works better. I find when using a dashboard, I pull from a variety of models for the opening page to get statistics about the site. I would use the DashboardController only for this general information. From the Dashboard, I would like to other pages that have the specific items you want to view/edit. This way if the admins need to access view/edit the same information as the users, you do not need to rewrite code. You can just update the security on that particular controller to allow for both groups.

    0 讨论(0)
提交回复
热议问题