Reputation: 657
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
Upvotes: 0
Views: 1454
Reputation: 146269
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'));
Upvotes: 1