httpoz / roles
Powerful package for handling roles and permissions in Laravel
Installs: 109 453
Dependents: 0
Suggesters: 0
Security: 0
Stars: 106
Watchers: 6
Forks: 32
Open Issues: 7
Requires
- php: ^8.0
- illuminate/cache: ^9.0
- illuminate/support: ^9.0
Requires (Dev)
- orchestra/database: ^7.0
- orchestra/testbench: ^7.0
- phpunit/phpunit: ^9.5.10
- dev-master
- v9.0.0
- 8.x-dev
- v8.1.0
- v8.0.2
- v8.0.1
- v5.0.0
- v4.0.0
- v3.3.0
- 3.2.0
- v3.1.0
- 3.0.x-dev
- v3.0.0
- 2.3.x-dev
- v2.3.0
- v2.2.2
- v2.2.1
- v2.2.0
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.0
- 1.4.x-dev
- v1.4.1
- v1.4.0
- v1.3.0
- v1.2.2
- v1.2.1
- v1.2.0
- v1.1.1
- v1.1.0
- v1.0.4
- v1.0.3
- v1.0.2
- v1.0.1
- v1.0.0
- dev-hotfix/79-performance-issues-from-always-reading-roles-from-cache
- dev-patch/refactoring
This package is auto-updated.
Last update: 2024-10-28 00:59:00 UTC
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
Slugable
trait, if you make a mistake and for example leave a space in slug parameter, it'll be replaced with a dot automatically, because ofstr_slug
function.
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
usersWithTrashed
method instead ofusers
.
Groups
if ($user->group() == 'application.managers') { // } if ($user->inGroup('application.managers')) { // if true do something }
If a user has multiple roles, method
group
returns 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.