Files
kulakpos_web/vendor/spatie/laravel-permission/src/Commands/AssignRole.php

66 lines
2.0 KiB
PHP
Raw Normal View History

2026-03-30 14:54:57 +07:00
<?php
namespace Spatie\Permission\Commands;
use Illuminate\Console\Command;
2026-04-18 20:32:18 +07:00
use Spatie\Permission\Contracts\Role;
2026-03-30 14:54:57 +07:00
use Spatie\Permission\Contracts\Role as RoleContract;
2026-04-18 20:32:18 +07:00
use Spatie\Permission\PermissionRegistrar;
2026-03-30 14:54:57 +07:00
class AssignRole extends Command
{
protected $signature = 'permission:assign-role
{name : The name of the role}
{userId : The ID of the user to assign the role to}
{guard? : The name of the guard}
2026-04-18 20:32:18 +07:00
{userModelNamespace=App\Models\User : The fully qualified class name of the user model}
{--team-id=}';
2026-03-30 14:54:57 +07:00
2026-04-18 20:32:18 +07:00
protected $description = 'Assign a role to a user';
2026-03-30 14:54:57 +07:00
2026-04-18 20:32:18 +07:00
public function handle(PermissionRegistrar $permissionRegistrar)
2026-03-30 14:54:57 +07:00
{
$roleName = $this->argument('name');
$userId = $this->argument('userId');
$guardName = $this->argument('guard');
$userModelClass = $this->argument('userModelNamespace');
2026-04-18 20:32:18 +07:00
if (! $permissionRegistrar->teams && $this->option('team-id')) {
$this->warn('Teams feature disabled, argument --team-id has no effect. Either enable it in permissions config file or remove --team-id parameter');
return;
}
2026-03-30 14:54:57 +07:00
// Validate that the model class exists and is instantiable
if (! class_exists($userModelClass)) {
$this->error("User model class [{$userModelClass}] does not exist.");
return Command::FAILURE;
}
$user = (new $userModelClass)::find($userId);
if (! $user) {
$this->error("User with ID {$userId} not found.");
return Command::FAILURE;
}
2026-04-18 20:32:18 +07:00
$teamIdAux = getPermissionsTeamId();
setPermissionsTeamId($this->option('team-id') ?: null);
/** @var Role $roleClass */
2026-03-30 14:54:57 +07:00
$roleClass = app(RoleContract::class);
$role = $roleClass::findOrCreate($roleName, $guardName);
$user->assignRole($role);
2026-04-18 20:32:18 +07:00
setPermissionsTeamId($teamIdAux);
2026-03-30 14:54:57 +07:00
$this->info("Role `{$role->name}` assigned to user ID {$userId} successfully.");
return Command::SUCCESS;
}
}