I am wondering if there is a better way of handling how I have my authenticated users in regards of different types of users.
I have a basic user and an administrator user. The basic user obviously will only have access to basic pages and the administrator user needs to have access to other pages that the basic user cannot have access to.
What I have been doing is: I created a super_user column in my table and adding:
if(Auth::user()->super_user == 0) {
return Redirect::to('/')->with('error', 'You do not have permission to access this page');
}
to each page that I do not want a basic user to be able to access. Now, this worked but I am starting to transition my apps to Laravel 5 and I am thinking there is a different way I can handle this.
Best way to handle user roles in your case is to use Middleware.
- Create middleware:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Admin
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$this->auth->getUser()->super_user) {
return redirect->to('/')
->with('error', 'You do not have permission to access this page');
}
}
return $next($request);
}
}
- Add it to
app\Http\Kernel.php
:
protected $routeMiddleware = [
'admin' => 'App\Http\Middleware\Admin',
];
- Use middleware in your routes:
Route::group(['middleware' => ['admin']], function() {
// your route
});