Validation in Laravel Artisan commands

One of the things I like most about using Laravel is that most everything I’ve needed to do so far is pretty intuitive.  If I try to code up something the way I think it’s supposed to work, usually it does.

I’ve been working on adding some new Artisan commands to my equipment database to handle some of the back-end administrative tasks that I’d normally have to fire up a browser for.

Naturally I want to validate the input.  Laravel’s got some really nice validation rules that would be nice to use in my new artisan commands.  The documentation covers doing validation on incoming HTTP requests, but isn’t clear on whether the Validator can be used more generically.

Looking at the documentation for manually creating validators, a Validator instance takes two arrays: an array with the data to be validated, and an array containing the validation rules.

It seemed like I could use the Validator facade pretty much anywhere as long as I had arrays of data and validation rules.  In my artisan commands, I added a use statement for the Validator facade,

use Illuminate\Support\Facades\Validator;

and the rest mostly followed the manual validator creation docs.

$validator = Validator::make($model->toArray(), [
  // validation rules
]);

if ($validator->fails()) {
  // show validation errors and exit
}
else {
  // do stuff with validated data
}

Much happiness ensued when I tested things out and saw that the validations were working just like I thought they should.


Discover more from Imablog

Subscribe to get the latest posts sent to your email.