use Spatie\Permission\Models\Permission;// Create a single permissionPermission::create(['name' => 'edit articles']);// Create with explicit guardPermission::create([ 'name' => 'edit articles', 'guard_name' => 'api']);
Roles group related permissions together. Instead of granting 10 individual permissions to a user, you can create an “Editor” role with those permissions and assign the role.
Roles have the same basic structure as permissions:
name: The role identifier (e.g., ‘editor’, ‘admin’)
guard_name: The authentication guard this role belongs to
Guards are Laravel’s way of defining different authentication systems. The web guard typically uses session-based authentication, while the api guard might use token-based authentication.
Common use cases for multiple guards:
Web vs API: Different permissions for web users and API consumers
Admin Panel: Separate admin authentication with different permissions
Multi-tenant: Different permission sets per tenant type
You cannot assign a permission from one guard to a user authenticated with a different guard. Laravel Permission will throw a GuardDoesNotMatch exception.
First, check if the user has the permission directly assigned via givePermissionTo().
2
Check Role Permissions
If not found, check if any of the user’s roles have that permission.
3
Return Result
Return true if found in either source, false otherwise.
// User has direct permission$user->givePermissionTo('edit articles');$user->can('edit articles'); // true// User has permission via role$role = Role::create(['name' => 'editor']);$role->givePermissionTo('publish articles');$user->assignRole('editor');$user->can('publish articles'); // true// User has no access$user->can('delete users'); // false
Use direct permissions for special cases or temporary access:
// User is a writer but needs temporary publish access$user->assignRole('writer');$user->givePermissionTo('publish articles');
Consistent Naming
Use a consistent naming convention throughout your application:
// Choose one style and stick with it// Dot notation'articles.create', 'articles.edit', 'articles.delete'// Or space notation'create articles', 'edit articles', 'delete articles'
Seed Permissions Early
Create all your permissions and roles in a seeder that runs during deployment:
class PermissionSeeder extends Seeder{ public function run(): void { // Clear cache app()[PermissionRegistrar::class]->forgetCachedPermissions(); // Create all permissions // Create all roles // Assign permissions to roles }}
Use Gates and Policies
Leverage Laravel’s authorization features alongside this package:
// In a Policypublic function update(User $user, Article $article){ return $user->can('edit articles') && $user->id === $article->author_id;}