CreateUserCommand.php (3097B)
1 <?php 2 3 namespace App\Console\Commands; 4 5 use Exception; 6 use Illuminate\Console\Command; 7 use function Laravel\Prompts\text; 8 use function Laravel\Prompts\password; 9 use function Laravel\Prompts\confirm; 10 11 12 class CreateUserCommand extends Command 13 { 14 /** 15 * The name and signature of the console command. 16 * 17 * @var string 18 */ 19 protected $signature = 'user:create {--u|username= : Username of the newly created user.} {--e|email= : E-Mail of the newly created user.}'; 20 21 /** 22 * The console command description. 23 * 24 * @var string 25 */ 26 protected $description = 'Manually creates a new home-erp user.'; 27 28 /** 29 * Execute the console command. 30 */ 31 public function handle() 32 { 33 // Enter username, if not present via command line option 34 $name = $this->option('username'); 35 if ($name === null) { 36 $name = text( 37 label: 'Please enter your username.', 38 required: true, 39 validate: fn(string $value) => match (true) { 40 strlen($value) > 255 => 'The username must not exceed 255 characters.', 41 default => null 42 } 43 ); 44 } 45 46 // Enter email, if not present via command line option 47 $email = $this->option('email'); 48 if ($email === null) { 49 $email = text( 50 label: 'Please enter your E-Mail.', 51 required: true, 52 validate: fn(string $value) => match (true) { 53 strlen($value) > 255 => 'The email must not exceed 255 characters.', 54 default => null 55 } 56 ); 57 } 58 59 // Always enter password from userinput for more security. 60 $password = password( 61 label: 'Please enter a new password.', 62 placeholder: 'password', 63 hint: 'Minimum 8 characters.', 64 required: true, 65 validate: fn(string $value) => match (true) { 66 strlen($value) < 8 => 'The password must be at least 8 characters.', 67 default => null 68 } 69 ); 70 $password_confirmation = password( 71 label: 'Please confirm the password.', 72 placeholder: 'password', 73 required: true, 74 validate: fn(string $value) => match (true) { 75 $password !== $value => 'The password must match what you previously entered.', 76 default => null 77 } 78 ); 79 80 // Verify password confirmation 81 if ($password !== $password_confirmation) { 82 $this->error('Incorrect password confirmation.'); 83 return Command::FAILURE; 84 } 85 86 $user = new \App\Models\User(); 87 $user->name = $name; 88 $user->email = $email; 89 $user->password = $password; 90 try { 91 $user->saveOrFail(); 92 } catch (Exception $e) { 93 $this->error('Failed to save user'); 94 return Command::FAILURE; 95 } 96 97 $this->info("Successfully registered user $name"); 98 } 99 }