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

Philippe Lonchampt
Jun 13, 2019 · 2 min read

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.

code16

About open source projects at CODE 16

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store