欢迎各位兄弟 发布技术文章
这里的技术是共享的
{
"require": {
"bican/roles": "1.4.*"
}
}
執行 Command Line composer update
config/app.php
'providers' => [
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
...
'Bican\Roles\RolesServiceProvider',
],
因為此次專案沒有用到 Bican Package 中的 Permission 功能,因此把
database/migrations
下的create_permissions_table
、create_permissions_role_table
、create_permissions_user_table
刪除後在執行php artisan migrate
執行 command line
$ php artisan vendor:publish
$ php artisan migrate
編輯 app/User.php
修改和增加以下內容:
// 增加的部份(Start)
use Bican\Roles\Contracts\HasRoleContract;
use Bican\Roles\Contracts\HasPermissionContract;
use Bican\Roles\Traits\HasRole;
use Bican\Roles\Traits\HasPermission;
// (End)
// 修改的部份 (Start)
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleContract, HasPermissionContract {
use Authenticatable, CanResetPassword, HasRole, HasPermission;
// (End)
要使用 Bican 套件時,記得在檔頭引入資源use Bican\Roles\Models\Role;
引入使用者資源請加上use App\User;
詳細如下:
use Bican\Roles\Models\Role;
use App\User;
$role = Role::create([
'name' => 'Admin',
'slug' => 'admin',
'description' => ''
]);
$user = User::find($id)->attachRole($role);
// 位使用者加上權限,$id 為 使用者ID,$role 則為 Role 的 ID 編號
如果需要一次符合多種類型的權限,可以傳入陣列。ex:User::find($id)->attachRole([1,2,3]);
可以使用以下方法來取得權限的資訊與判斷,請確認使否引入了 User、Role 資源!!!
在確認前要找到要確認的使用者$user = User::find($id);
//方法一
if ($user->is('admin')) // here checking by slug. You can pass an id or slug
{
return 'admin';
}
//方法二(魔術語法)
if ($user->isAdmin())
{
return 'admin';
}
if ($user->level() > 4)
{
// code
}
if ($user->is('admin|moderator')) // or $user->is('admin, moderator') and also $user->is(['admin', 'moderator'])
{
// if user has at least one role
}
if ($user->is('admin|moderator', 'all')) // or $user->is('admin, moderator', 'all') and also $user->is(['admin', 'moderator'], 'all')
{
// if user has all roles
}
$purviews = $user->roles;
var_dump($purviews);
foreach($purviews as $purview) {
echo $purview['name'], "<->";
echo $purview['slug'], "<br/>";
}
/*
* 刪除單筆 or 多筆權限
* 單筆:$user->detachRole(1);
* 多筆:$user->detachRole([1,2,3]);
*/
$user->detachRole($role);
//刪除所有權限
$user->detachAllRoles();
以下為加入會員登入系統
app/Services/Registrar.php
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
User::find($user->id)->attachRole($role_id);
return $user;
}
此時當使用者註冊時便會同時擁有 $role_id
這組權限。
題外: 使用內建的忘記密碼功能時,想要修改 Email 預設的標題,可以修改
app/Http/Controllers/Auth/PasswordController.php
如下:
public function __construct(Guard $auth, PasswordBroker $passwords)
{
$this->auth = $auth;
$this->passwords = $passwords;
$this->subject = '重設密碼Email標題';
$this->middleware('guest');
}
如此 重設密碼的email標題為你所設定的字串。
来自 http://kun0526-blog.logdown.com/posts/2015/03/02/laravel-5-bican-permissions-management-suite