|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use App\User; |
| 6 | +use Validator; |
| 7 | +use Illuminate\Console\Command; |
| 8 | + |
| 9 | +class CreateUser extends Command |
| 10 | +{ |
| 11 | + /** |
| 12 | + * The name and signature of the console command. |
| 13 | + * |
| 14 | + * @var string |
| 15 | + */ |
| 16 | + protected $signature = 'user:create |
| 17 | + {name : The name of the user} |
| 18 | + {email : Email used to login}'; |
| 19 | + |
| 20 | + /** |
| 21 | + * The console command description. |
| 22 | + * |
| 23 | + * @var string |
| 24 | + */ |
| 25 | + protected $description = 'Creates a new user for the application.'; |
| 26 | + |
| 27 | + /** |
| 28 | + * Create a new command instance. |
| 29 | + * |
| 30 | + * @return void |
| 31 | + */ |
| 32 | + public function __construct() |
| 33 | + { |
| 34 | + parent::__construct(); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Execute the console command. |
| 39 | + * |
| 40 | + * @return mixed |
| 41 | + */ |
| 42 | + public function handle() |
| 43 | + { |
| 44 | + $name = $this->argument('name'); |
| 45 | + $email = $this->argument('email'); |
| 46 | + $password = $this->secret('User password:'); |
| 47 | + |
| 48 | + $data = compact('name', 'email', 'password'); |
| 49 | + $validator = Validator::make($data, [ |
| 50 | + 'name' => 'required|max:255', |
| 51 | + 'email' => 'required|email|max:255|unique:users', |
| 52 | + 'password' => 'required|min:6', |
| 53 | + ]); |
| 54 | + if($validator->fails()) { |
| 55 | + foreach($validator->errors()->all() as $error) { |
| 56 | + $this->error($error); |
| 57 | + return 0; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + User::create([ |
| 62 | + 'name' => $data['name'], |
| 63 | + 'email' => $data['email'], |
| 64 | + 'password' => bcrypt($data['password']), |
| 65 | + ]); |
| 66 | + |
| 67 | + $this->info('User has been created.'); |
| 68 | + $this->comment('You can now login using the email and password entered here.'); |
| 69 | + } |
| 70 | +} |
0 commit comments