I want to split middleware auth to two role one is for admin and second for user but some route is use for all user and admin and few route is for admin only how can i split with route?
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
//Some route here
});
Route::group(['middleware' => ['guest']], function () {
//some route here
});
Here is my implementation for access control for admin and users(agents in my case) I have a boolean field in my user table (is_admin
) which is 0 for normal users and 1 for admins.
In your User model add this:
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
Create a new middlewares for Admin and Agent:
php artisan make:middleware Admin
php artisan make:middleware Agent
The middleware files will be created in App\Http\Middleware\
Add this to class inside Admin.php
:
public function handle($request, Closure $next)
{
if ( Auth::check() && Auth::user()->isAdmin() )
{
return $next($request);
}
return redirect('/agent');
}
Add this to Agent.php
public function handle($request, Closure $next)
{
if ( Auth::check() && !Auth::user()->isAdmin() )
{
return $next($request);
}
return redirect('/home');
}
After this register your middleware with laravel to do this add this to protected $routeMiddleware
in your Kernel.php
which is located at app\Http\Kernel.php
'admin' => 'App\Http\Middleware\Admin',
'agent' => 'App\Http\Middleware\Agent',
Make sure to create proper routes for redirection as we've mentioned in our middleware files. After this you are almost done. Now to verify if a user is admin or normal user add this to the constructor method of your controller.
Actions allowed only for admin users:
public function __construct()
{
$this->middleware('auth');
$this->middleware('admin');
}
Action allowed only for normal (agent) users:
public function __construct() {
$this->middleware('auth');
$this->middleware('agent');
}
Or you can also add middleware to your routes,
Route::group(['middleware' => 'admin'], function () {
//Some route here
});