Spatie Permissions Package Code Snippets

Check if a user has any role

$user->hasAnyRole(Role::all())

Assign a role by role name

$user->assignRole('Manager', 'Editor');

Remove a role by role name

$user->removeRole('Manager', 'Editor');

Remove all roles for a user (refrences this Github thread):

$user->roles()->detach();
$user->forgetCachedPermissions();

Securing routes with middleware

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
    'role:Editor|Admin|SuperAdmin'
])->group(function  ()  {
    Route::get('/dashboard',  function  ()  {  return view('dashboard');  })->name('dashboard');
});

Securing components inside a blade for roles

@role('Manager|SuperAdmin')
	<div>
		<button>Delete User</button>
	</div>
@endrole

Securing components inside a blade for permissions

@can('view settings button')
	<div>
		<button>Settings</button>
	</div>
@endcan

Remove all permissions from a role

$role->permissions()->detach();

Remove an array or a single permission from a role

$role->revokePermissionTo($permission);
comments powered by Disqus