Creating a console command that can handle multiple inputs.
Note: this code might require some additional editions.
php artisan make:command MakeUserCommand
Will create: app/Console/Commands/MakeUserCommand.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MakeUserCommand extends Command
{
protected $signature = 'command:name';
protected $description = 'Command description';
public function handle()
{
$name = 'name';
$message = 'Name: ';
$rules = ['required', 'string'];
return $this->askWithValidation($name, $rules, $message);
}
}
And askWithValidation
as a trait for reusability:
<?php
namespace App\Console\Commands\Concerns;
use Illuminate\Support\Facades\Validator;
trait WithInputValidation
{
public function askWithValidation(
string $name
string $message,
array $rules = [],
)
{
$answer = $this->ask($message);
// $this->options();
$validator = Validator::make(
[$name => $answer],
[$name => $rules]
);
if ($validator->passes())
{
return $answer;
}
$validatorList = $validator->errors()->all();
foreach ($validatorList as $error)
{
$this->error($error);
}
return $this->askWithValidation($message, $rules, $name);
}
}