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

Philippe Lonchampt
Jun 13 · 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:

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:

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:

… 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):

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

Philippe Lonchampt

Written by

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

code16

code16

About open source projects at CODE 16