-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(console): 通过编程式修改用户的 is_admin 字段 (#47)
- Loading branch information
1 parent
704a77a
commit 21ba1ae
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |