一、下载 laravel 5.1
composer create-project laravel/laravel=5.1.* laravel5.1_rbac
新建数据库 laravel5.1_rbac
修改 .evn 配置文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.1_rbac
DB_USERNAME=laravel5.1_rbac
DB_PASSWORD=laravel5.1_rbac
修改中国时区,在 config/app.php 中修改
'timezone' => 'PRC',
切换目录
cd laravel5.1_rbac
二、下载 romanbican/roles
打开:https://github.com/romanbican/roles
修改 composer.json:require 新增
"bican/roles": "2.1.*"
然后执行
composer update
config/app.php 的 providers 新增
Bican\Roles\RolesServiceProvider::class,
执行 artisan
php artisan vendor:publish --provider="Bican\Roles\RolesServiceProvider" --tag=config
php artisan vendor:publish --provider="Bican\Roles\RolesServiceProvider" --tag=migrations
执行数据迁移
php artisan migrate
配置 User 模型
use Bican\Roles\Traits\HasRoleAndPermission;
use Bican\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;
class User extends Model implements AuthenticatableContract,AuthorizableContract,CanResetPasswordContract,HasRoleAndPermissionContract
{
use Authenticatable, Authorizable, CanResetPassword, HasRoleAndPermission
{
HasRoleAndPermission ::can insteadof Authorizable;
}
三、使用 romanbican/roles
进入 tinker
php artisan tinker
创建 10 个用户
factory('App\User', 10)->create();
创建控制器
php artisan make:controller RolesController
创建角色:修改 app/Http/Controllers/RolesController
use Bican\Roles\Models\Role;
public function index()
{
Role::create([
'name' => 'Admin',
'slug' => 'admin',
'description' => '',
'level' => 1,
]);
Role::create([
'name' => 'Member',
'slug' => 'member',
'description' => '',
'level' => 2,
]);
Role::create([
'name' => 'Vip',
'slug' => 'vip',
'description' => '',
'level' => 3,
]);
Role::create([
'name' => 'Sponsor',
'slug' => 'sponsor',
'description' => '',
'level' => 4,
]);
return 'success';
}
注册路由:修改 app/Http/routes.php
Route::get('/roles', 'RolesController@index');
启动 serve
php artisan serve
访问:http://localhost:8000/roles,roles 表新增数据
创建权限:修改 app/Http/Controllers/RolesController
use Bican\Roles\Models\Permission;
public function index()
{
$createUsersPermission = Permission::create([
'name' => 'Create users',
'slug' => 'create.users',
'description' => '', // optional
]);
$deleteUsersPermission = Permission::create([
'name' => 'Delete users',
'slug' => 'delete.users',
]);
return 'success';
}
访问:http://localhost:8000/roles,permissions 表新增数据
设置用户角色:修改 app/Http/Controllers/RolesController
use App\User;
public function index()
{
$user = User::find(1);
$user->attachRole(1);
$user = User::find(2);
$user->attachRole(2);
return 'success';
}
访问:http://localhost:8000/roles,role_user 表新增数据
验证权限:修改 app/Http/Controllers/RolesController
public function index()
{
$user = User::find(1);
return [
'isAdmin' => $user->is('admin'),
'isMember' => $user->is('member'),
];
}