httpoz/roles
Composer 安装命令:
composer require httpoz/roles
包简介
Powerful package for handling roles and permissions in Laravel
README 文档
README
Simple package for handling roles in Laravel.
Installation
This package is very easy to set up. There are only a couple of steps.
Previous Versions
For Previous versions please see the releases page
Composer
Add the package to your project via composer.
composer require httpoz/roles:^v9.0
Config File And Migrations
To publish the package config's file and migrations to your application. Run this command inside your terminal.
php artisan vendor:publish --provider="HttpOz\Roles\RolesServiceProvider"
php artisan migrate
Enable HasRole Trait And Contract
Include HasRole trait and also implement HasRole contract inside your User model.
<?php use HttpOz\Roles\Traits\HasRole; use HttpOz\Roles\Contracts\HasRole as HasRoleContract; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable implements HasRoleContract { use Notifiable, HasRole; /// }
And that's it!
Usage
Creating Roles
$adminRole = \HttpOz\Roles\Models\Role::create([ 'name' => 'Admin', 'slug' => 'admin', 'description' => 'Custodians of the system.', // optional 'group' => 'default' // optional, set as 'default' by default ]); $moderatorRole = \HttpOz\Roles\Models\Role::create([ 'name' => 'Forum Moderator', 'slug' => 'forum.moderator', ]);
Because of
Slugabletrait, if you make a mistake and for example leave a space in slug parameter, it'll be replaced with a dot automatically, because ofstr_slugfunction.
Attaching And Detaching Roles
It's really simple. You fetch a user from database and call attachRole method. There is BelongsToMany relationship between User and Role model.
use App\User; $user = User::find($id); $user->attachRole($adminRole); // you can pass whole object, or just an id
$user->detachRole($adminRole); // in case you want to detach role $user->detachAllRoles(); // in case you want to detach all roles
Syncing Roles
You may also use the sync method to attach roles to a user model. Any roles that are not passed into the method will be detached from the user's roles. So, after this operation is complete, only the roles passed into the method will be attached to the user:
$user = App\User::find($id); $roles = [1, 4, 6]; // using the role IDs we want to assign to a user $user->syncRoles($roles); // you can pass Eloquent collection, or just an array of ids
Checking For Roles
You can now check if the user has required role.
if ($user->isRole('admin')) { // you can pass an id or slug // do something } // or if($user->hasRole('admin')) { // do something } // or if ($user->isAdmin()) { // }
And of course, there is a way to check for multiple roles:
In this case, a user has to have at least one of the given roles. Multiple options have been illustrated below that achieve the same goal.
if ($user->isRole('admin|forum.moderator')) { // do something } if($user->isRole('admin, forum.moderator')){ // do something } if($user->isRole(['admin', 'forum.moderator'])){ // do something } if($user->isOne('admin|forum.moderator')){ // do something } if($user->isOne('admin, forum.moderator')){ // do something } if($user->isOne(['admin', 'forum.moderator'])){ // do something }
In this case, a user has to have all the given roles. Multiple options have been illustrated below that achieve the same goal.
if ($user->isRole('admin|forum.moderator', true)) { // do something } if($user->isRole('admin, forum.moderator', true)){ // do something } if($user->isRole(['admin', 'forum.moderator'], true)){ // do something } if($user->isAll('admin|forum.moderator')){ // do something } if($user->isAll('admin, forum.moderator')){ // do something } if($user->isAll(['admin', 'forum.moderator'])){ // do something }
Find users by role
There are multiple ways to get a list of users by their given role.
Using the role's id
$admins = Role::find(1)->users;
Using the role's slug
$adminRole = Role::findBySlug('admin'); $admins = $adminRole->users;
Using the role's group
$adminRole = Role::where('group', 'forum.moderator')->first(); $admins = $adminRole->users;
If you use soft delete on your Users model, and want to include deleted users, you can use
usersWithTrashedmethod instead ofusers.
Groups
if ($user->group() == 'application.managers') { // } if ($user->inGroup('application.managers')) { // if true do something }
If a user has multiple roles, method
groupreturns the first one in alphabetical order (a better implementation of this will be explored).
Group is intended to collectively organise and assign permissions (Laravel's built-in authorization feature) to a role group that can be shared by multiple roles (examples and implementation to be added to documentation in future).
Blade Extensions
There are two Blade extensions. Basically, it is replacement for classic if statements.
@role('admin') // @if(Auth::check() && Auth::user()->isRole('admin')) // user is admin @endrole @group('application.managers') // @if(Auth::check() && Auth::user()->group() == 'application.managers') // user belongs to 'application.managers' group @endgroup @role('admin|moderator', 'all') // @if(Auth::check() && Auth::user()->isRole('admin|moderator', 'all')) // user is admin and also moderator @else // something else @endrole
Middleware
This package comes with VerifyRole and VerifyGroup middleware. You must add them inside your app/Http/Kernel.php file.
/** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ // ... 'role' => \HttpOz\Roles\Middleware\VerifyRole::class, 'group' => \HttpOz\Roles\Middleware\VerifyGroup::class, ];
Now you can easily protect your routes.
$router->get('/example', [ 'as' => 'example', 'middleware' => 'role:admin', 'uses' => 'ExampleController@index', ]); $router->get('/example', [ 'as' => 'example', 'middleware' => 'group:application.managers', 'uses' => 'ExampleController@index', ]);
It throws \HttpOz\Roles\Exceptions\RoleDeniedException or \HttpOz\Roles\Exceptions\GroupDeniedException exceptions if it goes wrong.
You can catch these exceptions inside app/Exceptions/Handler.php file and do whatever you want. You can control the error page that your application users see when they try to open a page their role is not allowed to. This package already has a view bundled with it that should have been published to resources/views/vendor/roles/error.blade.php when you published the package. Simply add the below condition inside your app\Exceptions\Handler.php's render function. Feel free to point to another view of your choice.
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { if ($exception instanceof \HttpOz\Roles\Exceptions\RoleDeniedException || $exception instanceof \HttpOz\Roles\Exceptions\GroupDeniedException) { return response()->view('vendor.roles.error', compact('exception'), 403); } return parent::render($request, $exception); }
Config File
You can change connection for models, slug separator, models path and there is also a handy pretend feature. Have a look at config file for more information.
Caching
The configuration for cache expiry is defaulted to 2 weeks (in seconds). You can update this value to suit your project specific needs.
License
This package is free software distributed under the terms of the MIT license.
httpoz/roles 适用场景与选型建议
httpoz/roles 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 111.24k 次下载、GitHub Stars 达 105, 最近一次更新时间为 2016 年 09 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「acl」 「laravel」 「roles」 「permissions」 「illuminate」 「httpoz」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 httpoz/roles 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 httpoz/roles 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 httpoz/roles 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Laravel Multiauth package
This package provides a flexible way to add Role-based Permissions to Laravel 6.x
This package provides a flexible way to add Role-based Permissions to Laravel
AclManager plugin for CakePHP 3.x
Alfabank REST API integration
Smile Retailer Admin
统计信息
- 总下载量: 111.24k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 106
- 点击次数: 22
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2016-09-02