osaris-uk/access

Role & Permission based access control package for Laravel

2.0 2023-07-07 16:40 UTC

This package is auto-updated.

Last update: 2024-05-07 18:42:00 UTC


README

Usage

For Laravel 5.5 - 5.7 use v1.3.2

After running the migrations, you can start using the package by adding the AccessTrait to your user model.

use OsarisUk\Access\AccessTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, AccessTrait;
}

By default all user accounts will be created with the 'user' role, this can be configured in the access config.

You can publish the config file with:

php artisan vendor:publish --provider="OsarisUk\Access\AccessServiceProvider" --tag="config"

This package will read your default user model from Laravel's auth config auth.providers.users.model.

Middleware

This package ships with AccessMiddleware. This allows you to protect your routes allowing access to users with specific roles:

Route::group(['middleware' => ['access:admin|moderator']], function () {
    //
});

Route::group(['middleware' => ['access:user']], function () {
    //
});

You can also allow access to users with specific permissions:

Route::group(['middleware' => ['access:user,create posts']], function () {
    //
});

Route::group(['middleware' => ['access:user,remove posts']], function () {
    //
});

Route::group(['middleware' => ['access:,edit posts']], function () {
    //
});

Blade Directives

This package integrates with the default Laravel Blade directive @can, this allows you to show content based on a users assigned permission including permissions they have been assigned through a role:

@can('edit posts')
    <a href="#">Edit Post</a>
@endcan

There is also a @role Blade directive included in this package, this allows you to show content based on a users assigned role:

@role('moderator')
    <a href="#">Remove Post</a>
@endrole

Available Methods

giveRoles(...$roles)
withdrawRoles(...$roles)
updateRoles(...$roles)
givePermissionTo(...$permissions)
withdrawPermissionTo(...$permissions)
updatePermissions(...$permissions)
hasRole(...$roles)
hasPermissionTo($permission)