Roles and permissions for laravel
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
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,
]
}
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,
],
],
];
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);
}
The UserRole enum has two comparison methods
$user->role->is(UserRole::Admin);
$user->role->isNot(UserRole::Admin);
composer test
Please see CHANGELOG for more information on what has changed recently.
The MIT License (MIT). Please see License File for more information.