1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| <?php
namespace App\Console\Commands;
use App\Models\User; use App\Services\UserService;
class InteractiveCommand extends BaseCommand { protected $signature = 'user:manage'; protected $description = 'Interactive user management'; public function handle(UserService $service): int { $action = $this->choice( 'What would you like to do?', ['Create User', 'Update User', 'Delete User', 'List Users', 'Exit'], 0 ); return match ($action) { 'Create User' => $this->createUser($service), 'Update User' => $this->updateUser($service), 'Delete User' => $this->deleteUser($service), 'List Users' => $this->listUsers(), 'Exit' => $this->exit(), default => self::FAILURE, }; } protected function createUser(UserService $service): int { $name = $this->ask('Enter user name'); $email = $this->ask('Enter user email'); $password = $this->secret('Enter password'); if (!$this->confirm("Create user {$name} ({$email})?")) { $this->info('Cancelled'); return self::SUCCESS; } $user = $service->create([ 'name' => $name, 'email' => $email, 'password' => $password, ]); $this->info("User created with ID: {$user->id}"); return self::SUCCESS; } protected function updateUser(UserService $service): int { $userId = $this->ask('Enter user ID'); $user = User::find($userId); if (!$user) { $this->error('User not found'); return self::FAILURE; } $name = $this->ask('Enter new name', $user->name); $email = $this->ask('Enter new email', $user->email); $service->update($user, [ 'name' => $name, 'email' => $email, ]); $this->info('User updated'); return self::SUCCESS; } protected function deleteUser(UserService $service): int { $userId = $this->ask('Enter user ID'); $user = User::find($userId); if (!$user) { $this->error('User not found'); return self::FAILURE; } if (!$this->confirm("Delete user {$user->name}? This cannot be undone.")) { $this->info('Cancelled'); return self::SUCCESS; } $service->delete($user); $this->info('User deleted'); return self::SUCCESS; } protected function listUsers(): int { $users = User::select(['id', 'name', 'email', 'created_at']) ->orderBy('created_at', 'desc') ->limit(20) ->get(); $this->table( ['ID', 'Name', 'Email', 'Created'], $users->map(fn($u) => [$u->id, $u->name, $u->email, $u->created_at->diffForHumans()]) ); return self::SUCCESS; } protected function exit(): int { $this->info('Goodbye!'); return self::SUCCESS; } }
|