【问题标题】:Laravel role management in viewLaravel 角色管理视图
【发布时间】:2014-04-11 22:48:09
【问题描述】:

我正在使用 entrust 和 confide 制作一个包含角色管理系统的 Laravel 应用程序。

因此,当浏览路径时(例如 /questions),应显示的刀片视图文件取决于用户类型。我通过在每个控制器功能中进行切换来解决这个问题

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);

    }


}

但我想这不是解决这个问题的最佳方法。我实际上是在控制器中寻找一种过滤。

所以我的问题是:处理这个问题的最佳方法是什么?

谢谢

【问题讨论】:

    标签: php laravel controller filtering roles


    【解决方案1】:

    不确定您在寻找什么,但您可以使用以下代码减少代码:

    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);
        }
    }
    

    或者,您也可以在 global.php 文件中注册一个异常 (InvalidArgumentException) 处理程序(而不是 try/catch):

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

    您也可以使用过滤器:

    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'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2021-04-28
      相关资源
      最近更新 更多