ahrengot / laravel-roles-and-permissions
User roles and permissions for Laravel
Requires
- php: ^8.1
- illuminate/contracts: ^10.0|^11.0
- spatie/laravel-package-tools: ^1.14.0
Requires (Dev)
- laravel/pint: ^1.0
- nesbot/carbon: ^2.63
- orchestra/testbench: ^8.0|^9.0
- pestphp/pest: ^2.0
- pestphp/pest-plugin-arch: ^2.0
- pestphp/pest-plugin-laravel: ^2.0
- spatie/laravel-ray: ^1.26
README
Roles and permissions for laravel
Installation
Install the package via composer
composer require ahrengot/laravel-roles-and-permissions
Run the install command to publish the migration, stubs, config file and a basic test
php artisan roles-and-permissions:install
Run the migration to add a role
column to your users table. Feel free to modify this migration as needed.
php artisan migrate
Configuring your User model
Add the HasPermissions
trait to your user model and an enum cast for the role column. Optionally you can add a default value for the role using the built-in $attributes
property.
use \Ahrengot\RolesAndPermissions\Traits\HasPermissions; use App\Enums\UserRole; class User extends Authenticatable { use HasPermissions; protected $casts = [ 'role' => UserRole::class, ]; // Optional default role protected $attributes = [ 'role' => UserRole::User, ] }
Configuring roles and permissions
Your permissions are configured in config/permissions.php
.
User roles are defined in App\Enums\UserRole.php
. Update these roles to fit your application needs.
Permissions are just simple strings, but this package provides a helper class in App/Permissions/Permission.php
that declare each permission as a constant. This provides better editor support and helps prevent typos.
The config file contains an example of defining various permissions for each user role:
return [ 'roles' => [ UserRole::Admin->value => [ Permission::AccessAdminPanel, Permission::CreateApiTokens, ], ], ];
Usage
In blade
<nav> @can(Permission::AccessAdminPanel) <a href="...">Admin panel</a> @endcan <a href="...">Other link</a> </nav>
In policies
public function create(User $user) { return $user->can(Permission::CreatePosts); }
Comparing user roles
The UserRole enum has two comparison methods
$user->role->is(UserRole::Admin); $user->role->isNot(UserRole::Admin);
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.