Guard is Role and Permission management system for Laravel
You can install the package via composer:
composer require amdadulhaq/guard-laravel
You can publish and run the migrations with:
php artisan vendor:publish --tag="guard-laravel-migrations"
php artisan migrate
Add HasRoles
Trait and UserContract
Interface on User Model
namespace App\Models;
use AmdadulHaq\Guard\Contracts\User as UserContract;
use AmdadulHaq\Guard\HasRoles;
# ...
class User extends Authenticatable implements UserContract
{
use HasRoles;
}
use AmdadulHaq\Guard\Models\Role;
Role::create(['name' => 'administrator']);
use AmdadulHaq\Guard\Models\Permission;
use AmdadulHaq\Guard\Models\Role;
$items = [
'role' => ['viewAny', 'view', 'create', 'update', 'delete', 'restore', 'forceDelete'],
'permission' => ['viewAny', 'view', 'create', 'update', 'delete'],
];
$role = Role::first();
foreach ($items as $group => $names) {
foreach ($names as $name) {
$permission = Permission::create(['name' => $group.'.'.$name]);
$role->givePermissionTo($permission);
}
}
use AmdadulHaq\Guard\Models\Permission;
use AmdadulHaq\Guard\Models\Role;
use App\Models\User;
$user = User::first();
$role = Role::first();
// Assign role
$user->assignRole($role);
$permission = Permission::first();
// Assign permission
$role->givePermissionTo($permission);
use AmdadulHaq\Guard\Models\Permission;
use AmdadulHaq\Guard\Models\Role;
use App\Models\User;
$user = User::first();
$role = Role::first();
// Revoke role
$user->revokeRole($role);
$permission = Permission::first();
// Revoke permission
$role->revokePermissionTo($permission);
use AmdadulHaq\Guard\Models\Permission;
use AmdadulHaq\Guard\Models\Role;
use App\Models\User;
$user = User::first();
$role = Role::first();
// Role check
$user->hasRole($role->name) // true or false
$permission = Permission::first();
// Permission check
$user->hasPermission($permission); // true or false
use Illuminate\Support\Facades\Gate;
// for permission
Gate::authorize('role.view');
// for role
Gate::authorize('administrator');
// for permission
$this->authorize('role.view');
// for role
$this->authorize('administrator');
use Illuminate\Support\Facades\Route;
// for permission
Route::get('/', function () {
// ...
})->middleware('can:role.view');
// for role
Route::get('/', function () {
// ...
})->middleware('can:administrator');
// for permission
@can('role.view')
It's works
@endcan
// for role
@can('administrator')
It's works
@endcan
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.