Using Laravel Validation in Console Commands

Tom Ellis
3 min readMay 10, 2018

--

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:

php artisan make:command CreateStaffCommand

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:

<?php

namespace
App\Console\Commands;

use Illuminate\Console\Command;

class CreateStaffCommand extends Command
{
/**
* The name and signature of the console command.
*
*
@var string
*/
protected $signature = 'command:name';

/**
* The console command description.
*
*
@var string
*/
protected $description = 'Command description';

/**
* Create a new command instance.
*
*
@return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
*
@return mixed
*/
public function handle()
{
//
}
}

Setup Signature & Description

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

/**
* The name and signature of the console command.
*
*
@var string
*/
protected $signature = 'staff:create';

/**
* The console command description.
*
*
@var string
*/
protected $description = 'Create staff user';

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

public function __construct()
{
parent::__construct();
}

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:

/**
* The Artisan commands provided by your application.
*
*
@var array
*/
protected $commands = [
\App\Console\Commands\CreateStaffCommand
];

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:

$firstName = $this->ask('First Name?');
$lastName = $this->ask('Last Name?');
$email = $this->ask('Email ?');
$password = $this->secret('Password ?');

Validate the Input

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

$validator = Validator::make([
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'password' => $password,
], [
'first_name' => ['required'],
'last_name' => ['required'],
'email' => ['required', 'email', 'unique:staff,email'],
'password' => ['required', 'min:8'],
]);

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:

if ($validator->fails()) {
$this->info('Staff User not created. See error messages below:');

foreach ($validator->errors()->all() as $error) {
$this->error($error);
}
return 1;
}

Now the following line from above:

$validator->errors()->all()

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:

php artisan staff:create

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:

Staff::create([
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'password' => $password,
]);

$this->info('Staff Account created.');

return 0;

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

Summary

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

--

--

Tom Ellis
Tom Ellis

Written by Tom Ellis

PHP and JavaScript hacker. Symfony and Laravel tinkerer. Open source developer.

No responses yet