Skip to content

Commit

Permalink
feat(console): 通过编程式修改用户的 is_admin 字段 (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaiyuxin103 committed Nov 2, 2024
1 parent 704a77a commit 21ba1ae
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions app/Console/Commands/UpdateUserToAdmin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Validation\Rule;

use function Laravel\Prompts\text;

class UpdateUserToAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:update-user-to-admin {--id=}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Update user to admin';

/**
* Execute the console command.
*/
public function handle(): void
{
if ($id = (int) $this->option('id')) {
$user = User::find($id);
if ($user) {
$user->is_admin = true;
$user->save();
$this->info("User with ID {$id} has been updated to admin.");

return;
}
$this->error("User with ID {$id} not found.");
} else {
$this->table(
headers: ['ID', 'Name', 'Email'],
rows: User::select(['id', 'first_name', 'last_name', 'email'])->get()->map(fn ($user) => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
])->toArray()
);

$id = text(
label: 'Enter the user ID to update to admin:',
required: true,
validate: ['required', 'numeric', Rule::exists('users', 'id')->whereNull('deleted_at')],
);

$user = User::find($id);
$user->is_admin = true;
$user->save();
}
}
}

0 comments on commit 21ba1ae

Please sign in to comment.