smorken/roles

Roles helper for Laravel

v10.4.3 2024-09-12 18:15 UTC

README

License

This software is open-sourced software licensed under the MIT license

The Laravel framework is open-sourced software licensed under the MIT license

Requirements

Installation

Add to your Laravel app composer.json

"require": {
    "smorken/roles": "^6.0"
}

$ composer update

The service provider should automatically register itself.

If not, add service provider to config/app.php

'providers' => [
...
    \Smorken\Roles\ServiceProvider::class,

Publish the needed files (if you are planning to override them)

$ php artisan vendor:publish --provider="Smorken\Roles\ServiceProvider" --tag=views #config also available

Edit the config/roles.php if you want to have different roles allowed initially.

Run the migrations (might need to dump-autoload again)

$ php artisan db:seed --class="RoleSeeder"

Use

This is super simple scaling set of roles. Any role with a higher level will have access to any role below it.

Authorization is handled via Gates. You can create your own or use the built-in static method in Smorken\Roles\ServiceProvider to add them to the AuthServiceProvider

\App\Providers\AuthServiceProvider

<?php
/**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        // ...
        $this->registerPolicies();
        \Smorken\Roles\ServiceProvider::defineGates($this->app);
    }

If you use the default method, each role will be assigned a gate named "role-[role code]".

The gates are available in blade files via the blade shortcut @can('role-role-code') eg. @can('role-super-admin').

Gates are available on routes:

<?php
Route::group([
    'prefix' => 'admin',
    'middleware' => ['auth', 'can:role-admin'],
    'namespace' => 'Admin'
],
function () {
});

Gate facade:

<?php
//boolean check
if (Gate::allows('role-manage')) {

}
if (Gate::denies('role-super-admin')) {

}
if (Gate::forUser($user)->allows('role-admin')) {

}
//authorize check (throw AuthorizationException on failure)
Gate::authorize('role-manage');