<?php
namespace App\Console\Commands;
use App\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'createUser';
/**
* The console command description.
*
* @var string
*/
protected $description = 'create new user for system manually';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->line($this->description);
// 获取输入的数据
$data = [
'name' => $this->ask('What\'s your name?'),
'email' => $this->ask('What\'s your email?'),
'password' => $this->secret('What\'s your password?'),
'password_confirmation' => $this->secret('Pleas confirm your password.')
];
// 验证输入内容
$validator = $this->makeValidator($data);
if ($validator->fails()) {
foreach ($validator->errors()->toArray() as $error) {
foreach ($error as $message) {
$this->error($message);
}
}
return;
}
// 向用户确认输入信息
if (!$this->confirm('Confirm your info: ' . PHP_EOL . 'name:' . $data['name'] . PHP_EOL . 'email:' . $data['email'] . PHP_EOL . 'is this correct?')) {
return;
}
// 注册
$user = $this->create($data);
event(new Registered($user));
$this->line('User ' . $user->name . ' successfully registered');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function makeValidator($data)
{
return Validator::make($data, [
'name' => 'required|string|max:255|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed'
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create($data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
}
}