Laraccess - User Roles & Role Inheritance
Works with Laravel 5.4, (*1)
This package allows to save roles in a database.
Roles can inherit other roles too., (*2)
It includes blade directives & middleware, (*3)
Install
You can install the package via composer:
``` bash
$ composer require mashyindustries/laraccess, (*4)
This service provider must be installed.
```php
// config/app.php
'providers' => [
...
Mashy\Laraccess\LaraccessServiceProvider::class,
];
You can publish the migration with:, (*5)
php artisan vendor:publish --provider="Mashy\Laraccess\LaraccessServiceProvider" --tag="migrations"
The package assumes that your users table name is called "users". If this is not the case
you should manually edit the published migration to use your custom table name., (*6)
After the migration has been published you can create the role tables with:, (*7)
php artisan migrate
You can publish the config-file with:, (*8)
php artisan vendor:publish --provider="Mashy\Laraccess\LaraccessServiceProvider" --tag="config"
Usage
First add the Mashy\Laraccess\Traits\HasRoles trait to your User model., (*9)
use Mashy\Laraccess\Traits\HasRoles;
class User
{
use HasRoles;
// ...
}
This package allows for users to be associated with roles., (*10)
You can create roles with:, (*11)
use Mashy\Laraccess\Models\Role;
$role = Role::create([
'name' => 'Writer', //optional
'slug' => 'writer', //required
'description' => '' //optional
]);
The HasRoles adds collections to your models., (*12)
$roles = $user->roles(); // returns a collection
Using Roles
A role can be assigned to a user:, (*13)
$user->assignRole('writer');
// you can also assign multiple roles at once
$user->assignRole('writer', 'admin');
$user->assignRole(['writer', 'admin']);
A role can be removed from a user:, (*14)
$user->removeRole('writer');
Roles can also be synced :, (*15)
//all current roles will be removed from the user and replace by the array given
$user->syncRoles(['writer', 'admin']);
You can determine if a user has a certain role:, (*16)
$user->hasRole('writer');
You can also determine if a user has any of a given list of roles:, (*17)
$user->hasAnyRole(['writer', 'admin']);
You can also determine if a user has all of a given list of roles:, (*18)
$user->hasAllRoles(['writer', 'admin']);
Using blade directives
This package also adds Blade directives to verify whether the
currently logged in user has all or any of a given list of roles., (*19)
@role('writer')
I'm a writer!
@else
I'm not a writer...
@endrole
@hasanyrole(['writer', 'admin'])
I have one or more of these roles!
@else
I have none of these roles...
@endrole
@hasallroles(['writer', 'admin'])
I have all of these roles!
@else
I don't have all of these roles...
@endrole
You can use Laravel's native @can directive to check if a user has a certain permission., (*20)
Using a middleware
Information coming soon..., (*21)
Inheritance
Information coming soon..., (*22)
Credits
This package was based on Spatie/Laravel-Permission, (*23)
Alternatives