遵循以下步驟: -
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一個新的文件\中間件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將下面的代碼\核心。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]');
});