dtdfj08626 2014-03-08 09:59 采纳率: 0%
浏览 10
已采纳

Laravel角色管理在视野中

I'm making a Laravel application that includes a role management system, using entrust and confide.

So when a route is browsed (eg /questions), the blade view file that should be displayed depends on the user type. I solved this problem by making a switch in every controller function

public function getQuestions(){
    $questions = Question::all();

    switch(Auth::User()->getRoleName()){
        case 'Moderator':
        return View::make('questions.moderator.index',array('questions'=>$questions));
        break;

        case 'Teacher':
        return View::make('questions.teacher.index',array('questions'=>$questions));
        break;

        case 'Student':
        return View::make('questions.student.index',array('questions'=>$questions));
        break;

        default:
        return App:abort(404);

    }


}

But I guess this isn't the best way to solve this problem. I'm actually looking for a kind of filtering in the controller.

So my question is: what would be the best way to handle this ?

Thanks

展开全部

  • 写回答

1条回答 默认 最新

  • douqiao6563 2014-03-08 10:40
    关注

    Not sure what you looking for but you can reduce the code using this:

    public function getQuestions(){
        try {
            $role = strtolower(Auth::User()->getRoleName());
            $questions = Question::all();
            return View::make("questions.{$role}.index", compact('questions'));
        } catch(InvalidArgumentException $e) {
            // create a view "app/views/roleNotFound.blade.php"
            return Response::view('errors.roleNotFound', array(), 404);
        }
    }
    

    Alternatively you may also register an exception (InvalidArgumentException) handler in global.php file (instead of try/catch):

    App::error(function(InvalidArgumentException $exception, $code)
    {
        Log::error($exception);
        return Response::view('errors.roleNotFound', array(), $code);
    });
    

    You may also use a filter:

    Route::filter('role', function($route, $request){
    
        // depending on role, you may redirect to a
        // different route, for example; if not admin
        // then redirect to home page or whatever
        if(Auth::check()) {
            $role = strtolower(Auth::User()->getRoleName());
            if($role != 'admin') return Redirect::to('/');
        }
        else {
            // return to som url if not login
            // or whatever you want
        }
    });
    
    Route::get('/questions', array('before' => 'role:', 'uses' => 'Question@getQuestions'));
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部