Выполните следующие действия: -
1) Создать новую таблицу в PHPMyAdmin
CREATE TABLE `role` (
`id` int(10) UNSIGNED NOT NULL,
`role_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`role_description` text COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT
ALTER TABLE `role`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `role`
--
ALTER TABLE `role`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
2) Добавить внешний ключ в таблице пользователей
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_role` int(11) NOT NULL DEFAULT '0',
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`status` enum('0','1','2') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT;
3) Добавить ниже код в пользовательской модели, т.е. user.php App/User.php
/**
* Description : check user role which type of users login
*/
public function role()
{
return $this->hasOne('App\Role', 'id', 'user_role');
}
/**
* Description : check has role if user has any role assigned
*/
public function hasRole($roles)
{
//die('inside hasRole');
$this->have_role = $this->getUserRole();
// Check if the user is a root account
if($this->have_role->role_name == 'Admin') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
/**
* Description : check role from database
*/
private function getUserRole()
{
return $this->role()->getResults();
}
//
private function checkIfUserHasRole($need_role)
{
return (strtolower($need_role)==strtolower($this->have_role->role_name)) ? true : false;
}
4) Создайте новый файл в \ приложения \ Http \ Middleware с именем CheckRole.php добавить ниже код в этом файле
<?php
namespace App\Http\Middleware;
// First copy this file into your middleware directory
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckRole{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Get the required roles from the route
$roles = $this->getRequiredRoleForRoute($request->route());
// Check if a role is required for the route, and
// if so, ensure that the user has that role.
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}
return redirect('admin/logout');
/*return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);*/
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
5) Заменить приведенный ниже код в \ приложения \ Http \ Kernel.PHP
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
С ниже код
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'CheckRole' => [
'web',
'auth',
'roles'
],
'api' => [
'throttle:60,1',
'bindings',
],
];
И
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
С ниже кода
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'roles' => 'App\Http\Middleware\CheckRole',
];
6) наиболее важный момент вашей Разгром файлов \ маршрутов \ web.php должно быть что-то вроде ниже контроллера может быть варьироваться в зависимости от ваших требований
Auth::routes();
Route::get('/', 'Auth\[email protected]');
Route::group(['middleware' => ['CheckRole'], 'roles' => ['admin']], function() {
//Route::get('/home', '[email protected]');
Route::get('/admin/dashboard', '[email protected]');
//Route::get('/home', '[email protected]');
});
Route::group(['middleware' => ['CheckRole'], 'roles' => ['employee']], function() {
//Route::get('/home', '[email protected]');
Route::get('/employee', '[email protected]');
});