Ir al contenido principal

Spatie/Laravel-Permission quick reference

 spatie/laravel-permission howto add a role to a user

Respuesta rápida

To add a role to a user using the Spatie laravel-permission package, you must first ensure your User model uses the HasRoles trait.  Once configured, you can assign roles directly using the assignRole method or by chaining it with user creation. 

1. Prepare the User Model

Add the HasRoles trait to your User model:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

2. Assign a Role to an Existing User

Retrieve the user and call assignRole with the role name or instance:

$user = User::find(1);
$user->assignRole('admin');

// Assign multiple roles at once
$user->assignRole(['writer', 'admin']);
$user->assignRole(['writer', 'admin']); // or as an array

3. Assign a Role During User Creation

Chain the assignRole method directly after creating the user:

$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
])->assignRole('editor');

4. Assign Roles in Seeders

In database seeders, you can assign roles to existing users or create new users with roles:

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

// Create roles and permissions first
$adminRole = Role::create(['name' => 'admin']);
$permission = Permission::create(['name' => 'edit articles']);
$adminRole->givePermissionTo($permission);

// Assign role to user
$user = User::find(1);
$user->assignRole('admin');

Key Methods

  • assignRole($role): Adds a role to the user. 

  • syncRoles($roles): Replaces all existing roles with the provided list.

  • removeRole($role): Removes a specific role from the user.

  • hasRole($role): Checks if the user has a specific role.

artisan tinker to query spatie/permission roles and add one

Run php artisan tinker and use these commands directly in the REPL:

// Import the Role model
use Spatie\Permission\Models\Role;

// List all existing roles
Role::all();

// Find a role by name
Role::findByName('admin');

// Create a new role (if it doesn't exist)
$role = Role::firstOrCreate(['name' => 'editor']);

// Assign it to a user
$user = App\Models\User::find(1);
$user->assignRole('editor');

// Verify
$user->getRoleNames();

Quick reference in tinker:

TaskCommand
List rolesRole::all()
Find by nameRole::findByName('admin')
Create roleRole::create(['name' => 'admin'])
Assign to user$user->assignRole('admin')
Remove from user$user->removeRole('admin')
Check user roles$user->getRoleNames()
Clear cached permissionsapp('permission.cache')->forget()

Tip: If you're in a local environment and permissions seem stale after changes, call app('permission.cache')->forget() to clear the cache. 

Comentarios