Using Laravel Validation in Console Commands

Validation in Laravel is covered a great deal in the docs, but is more focused on using them in Controllers, but theres nothing stopping you from using them in other places, Console Commands for example. In this article we’re going to create a console command for create a staff user and use the Laravel Validator to validate our input from the command.

Building Our Console Command

We’re going to write a console command for create a staff user. To give us a base command to edit we’ll use the make:command command:

I always suffix my commands with Command but you don’t have to.

Running that will generate the CreateStaffCommand class into app/Console/Commands and give us something like this:

Setup Signature & Description

First we’ll update our signature (command name) and description to be something more appropriate:

We can also get rid of the the following as we don’t need it:

Add Command to Console Kernel

Next so the application knows about the console command you need to register it with the Console Kernel. You can find it in app/Console/Kernel.php. Now we need the add it to the $commands array:

Get User Input

Now we’re ready to get the user input for the staff details. We can use the ask helper for that and the secret helper for password:

Validate the Input

Now we have the data we can validate it, we’ll use the Validator facade to make our validator:

And then we can validate the input and get any error messages to output. New people to Laravel that use the ValidateRequests trait in their controllers might not ever manually get the errors from the validator.

So below we’re checking the the validation has failed and getting any errors:

Now the following line from above:

We get all the errors messages stored and do any replacements or translation changes before returning an array of the final error messages, meaning all we have to do is loop over them and split them out.

So if we were to run the console command now:

We’ll see the following output (I’m use iTerm2 so the colours may be different to yours):

Great, so our validation is working.

Create the Staff User

Now we can move on to creating the staff user and outputting a success message:

And if we run the command again, this time filling in the details, we should see something like:


And there we have it, how to make use of the Laravel Validator in Console Commands.

PHP and JavaScript hacker. Symfony and Laravel tinkerer. Creator of TomahawkPHP

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