How to validate user input in a Laravel Artisan console command?

Philippe Lonchampt
code16
Published in
2 min readJun 13, 2019

Here’s a quick tip to solve an issue I had today: I wrote a Laravel Artisan console command to allow the creation of a new user via the command line. For this project, some fields are required for the user, like first and last name for instance.

Laravel Artisan console commands allows inputs, via the ask() method:

$name = $this->ask("What's his/her name?");

But it can be tricky if you require this value to be set; in this situation, you can declare required fields as command arguments, like so:

app:create_user {first_name} {last_name}

But it’s less easy for the user, and what if there’s many fields? More important: what if you want to validate a min length, or an email?

Ultimately, I wanted the simplicity of the Artisan API with the power of the Laravel Validation. I wanted to be able to write this:

$name = $this->askValid(
'What's his/her name?',
'last_name',
['required','min:3]
);

… where the first argument is the question, the second is the field name and the third is an array of validation rules. Last, I didn’t want the user to be kicked out from the command in case of a validation error. We should display the validation message and re-prompt the question.

So here’s the result of that:

It turned out it was quite easy to make this work: here’s the code for the askValid() method (which can be transferred to a trait):

protected function askValid($question, $field, $rules)
{
$value = $this->ask($question);

if($message = $this->validateInput($rules, $field, $value)) {
$this->error($message);

return $this->askValid($question, $field, $rules);
}

return $value;
}


protected function
validateInput($rules, $fieldName, $value)
{
$validator = Validator::make([
$fieldName => $value
], [
$fieldName => $rules
]);

return $validator->fails()
? $validator->errors()->first($fieldName)
: null;
}

So clean and simple that I’m thinking it could be useful to other Laravel dev: maybe I’ll propose a PR for the Laravel framework—or feel free to do it before me.

--

--

Philippe Lonchampt
code16
Editor for

Developer and founder of Code 16, maintainer of Laravel Sharp.