I have 3 user roles: admin, customer and employee.
Each role will be redirected to a specific dashboard once logged in, eg: - Admin: website.com/admin - Customer: website.com/customer - Employee: website.com/employee
At this time, all can be accessed by going through those URLs regardless of which user role I'm using.
What is the easiest way to restrict customer from opening admin & employee dashboards? And restrict employee from opening admin & customer dashboards?
Laravel version 5.2.45 PHP version 7.2 I'm using a shared hosting provider. Thank you
try reading this, is very helpful
https://laravel.com/docs/5.7/middleware#assigning-middleware-to-routes
you can assign existent middlewares like auth
or auth.basic
or passing your own check role Class like this
use App\Http\Middleware\CheckAge;
Route::get('admin/profile', function () {
//
})->middleware(CheckAge::class);
What I would do in your case I would create a helper function within your User Model like:
function isAdmin(){
return $this->role == 0;
}
I would created one for each role and then you can use this functions in the View controller for example:
if(auth()->user()->isAdmin()){
return view('admin.dashboard');
}
else{
return view('guest.dashboard');
}
And also finally if you want to create a middleware to control the access to certain routes or controllers:
php artisan make:middleware AdminUser
and then within the handle function:
public function handle($request, Closure $next)
{
if (!auth()->user()->isAdmin) {
return redirect('home');
}
return $next($request);
}