Manage user permissions and roles in your Laravel application by domain driven rules.
$user->assignRole('admin');
$user->hasRole('admin'); // true
Define roles and permissions in config/permission.php
.
'role' => [
'admin' => [
'news/#', // Allow all paths beginning with news/
],
'editor' => [
'news/#',
'!news/delete', // Explicitly forbid news/delete
],
'user' => [
'news/show', // Explicitly allow news/show
],
]
Check permissions by
$admin->hasPermission('news/delete'); // true
$editor->hasPermission('news/delete'); // false
$user->hasPermission('news/delete'); // false
composer require sourceboat/laravel-static-permission
use HasRoles;
Define roles in config/permission.php
.
// config/permission.php
'roles' => [
'role_name' => [],
'admin' => [],
],
Add a role to a model.
$model->assignRole('admin');
Check role via:
$model->hasRole('admin');
$model->getRoleName(); // return admin
Permissions are based on the MQTT syntax and specified as path. Thus, individual security levels can be mapped and generally released via wildcards.
$model->hasPermission('users/show/email');
$model->hasPermission(['users/show', 'users/edit']);
$model->hasAnyPermission('users/show/email');
$model->hasAnyPermission(['users/show', 'users/edit']);
+
Wildcard for one level#
Wildcard for everything following!
Before the permission - prohibits permission
Define roles and permissions in config/permission.php
.
// config/permission.php
'roles' => [
'role_name' => [
'users/+/foo'
],
'admin' => [
'users/#',
'!users/create',
],
],
Use Blade directives in your views.
@role('admin')
Show if user is admin
@endrole
@unlessrole('admin')
Show if user is not admin
@endunlessrole
@permission('user/edit')
Show if user has rights to user/edit
@endpermission
Use several permissions.
@permission('user/edit|user/create')
Show if user has rights to user/edit AND user/create
@endpermission
@anypermission('user/edit|user/create')
Show if user has rights to user/edit OR user/create
@endanypermission
Add the middleware to your src/Http/Kernel.php
use Sourceboat\Permission\Middlewares\RoleMiddleware;
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'role' => RoleMiddleware::class
]
}
And use it like
Route::group(['middleware' => ['role:admin']], function () {
//
})
Example Config
<?php
// config/permission.php
return [
/**
* Column name of the model
*/
'column_name' => 'role',
/**
* Roles with permissions
*
* - `+` Wildcard one level
* - `#` Wildcard everything following
* - `!` Before the permission - prohibits permission
*
* 'admin' => [
* 'users/#',
* 'users/+/field',
* '!users/create'
* ]
*/
'roles' => [],
];
composer test
See releases for details.
composer lint:phpcs
composer lint:phpmd
This package is heavily inspired by Spatie / laravel-permission.
The MIT License (MIT). Please see License File for more information.