Authenticating a user role in Laravel and protecting a route
authentication, laravel, laravel-routing, roles
Solution
You have used `auth` filter so you should check in the `auth` filter in `app/filters.php` file:
Route::filter('auth', function($route, $request)
{
// Login check (Default)
if (Auth::guest()) return Redirect::guest('login');
// Admin check
if(!in_array('admin', Auth::user()->roles->toArray())) {
return Redirect::to('/'); // Redirect home page
}
});
You may use a different filter, for example:
Route::get('admin', function()
{
return View::make('admin.index');
})->before('isAdmin');
Declare the custom `isAdmin` filter in `app/filters.php`:
Route::filter('isAdmin', function($route, $request)
{
if(!Auth::check()) return Redirect::guest('login');
if( !in_array('admin', Auth::user()->roles->toArray()) ) {
return Redirect::to('/'); // Redirect home page
}
});
Problem
I have taken advice from people here and given Laravel a try, I have been trying to create a user authentication system. I am having trouble translating what I know works in PHP to Laravel using Eloquent. What I am trying to do here is identify a user, their roles, if the user has a role of admin they can access the route /admin I know I can use a package such as Entrust but that is not really helping me learn. I have created Models for both User and Role. I also have a lookup table called role_user with a user_id and role_id. In User.php I have ``` public function roles(){ return $this->belongsToMany('Role', 'users_roles'); } ``` In Role.php I have ``` public function users() { return $this->belongsToMany('User', 'users_roles'); } ``` I know if I used ``` $roles = user::find(1)->roles; return ($roles); ``` It will and does return the correct user id (1) and the roles assigned to that user. Now what I am struggling with is how to pick out the admin role and only if the user has this will it allow access to /admin The route should essentially be ``` Route::get('admin', function() { return View::make('admin.index'); })->before('auth'); ``` What I can't figure how/where/should I check for the admin role first and how to then apply that to the auth check to only permit an admin access to the route. Any help appreciated. Lee