本文目標(biāo)
完成Entrust的配置
安裝zizaco/entrust Package
zizaco/entrust是Laravel下基于角色的權(quán)限管理方案寞钥。
1.修改文件composer.json
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"gregwar/captcha": "1.*",
"zizaco/entrust": "dev-laravel-5"
},
2.在終端運(yùn)行命令
composer install
// or
composer update
3.在文件config/app.php
的providers
數(shù)組和aliase
數(shù)組分別添加
// providers
Zizaco\Entrust\EntrustServiceProvider::class
// aliase
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
4.在文件app/Http/Kernel.php
的$routeMiddleware
添加
'role' => Zizaco\Entrust\Middleware\EntrustRole::class,
'permission' => Zizaco\Entrust\Middleware\EntrustPermission::class,
'ability' => Zizaco\Entrust\Middleware\EntrustAbility::class,
5.Entrust會(huì)根據(jù)文件config/auth.php
的model
來選擇用戶模型氛濒,如下:
'model' => App\Models\User::class
執(zhí)行以下命令生成配置文件config/entrust.php
php artisan vendor:publish
修改配置文件entrust.php
如下:
'role'=>'App\Models\Role'
'permission'=>'App\Models\Permission'
6.生成數(shù)據(jù)庫遷移文件并執(zhí)行
php artisan entrust:migration
php artisan migrate
7.生成自動(dòng)加載
composer dump-autoload
管理模型
為了使用Entrust,我們需要新建兩個(gè)模型,在終端運(yùn)行以下命令:
// 角色模型
php artisan make:model Models/Role
// 權(quán)限模型
php artisan make:model Models/Permission
Role.php
<?php
namespace App\Models;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
protected $guarded = [];
}
Permission.php
<?php
namespace App\Models;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
protected $guarded = [];
}
為了配合Entrust的使用关面,需要修改User.php的代碼
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, EntrustUserTrait{
Authorizable::can insteadof EntrustUserTrait;
EntrustUserTrait::can as hasPermission;
}
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
}
完成上述所有操作之后演怎,Entrust的配置就完成了。