ahrengot/laravel-roles-and-permissions

User roles and permissions for Laravel

1.0.0 2023-08-02 12:23 UTC

This package is auto-updated.

Last update: 2024-05-01 00:06:15 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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.