spatie/laravel-permission howto add a role to a user
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 array3. 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.
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:
| Task | Command |
| List roles | Role::all() |
| Find by name | Role::findByName('admin') |
| Create role | Role::create(['name' => 'admin']) |
| Assign to user | $user->assignRole('admin') |
| Remove from user | $user->removeRole('admin') |
| Check user roles | $user->getRoleNames() |
| Clear cached permissions | app('permission.cache')->forget() |
Tip: If you're in a
localenvironment and permissions seem stale after changes, callapp('permission.cache')->forget()to clear the cache.
- Obtener enlace
- X
- Correo electrónico
- Otras aplicaciones
- Obtener enlace
- X
- Correo electrónico
- Otras aplicaciones
Comentarios