Laravel

Validate Console Command Input With the Command Validator Package

2024-9-18

Laravel News

Validate Console Command Input With the Command Validator Package


The Command Validator package by Andrea Marco Sartori makes validating the input of console commands a cinch using Laravel's beloved Validator. All the Laravel Validator rules you know and love work with this package, along with any custom validation rules.

This package integrates with your application's console commands using the provided ValidatesInput trait, which includes an abstract rules() method. The command signature looks like the following:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Cerbero\CommandValidator\ValidatesInput;

class SampleCommand extends Command
{
    use ValidatesInput;
    
    protected $signature = 'app:sample {--start-date=}';

    // ...

    public function rules(): array
    {
        return ['start-date' => 'date_format:Y-m-d'];
    }
}

I find it really neat that you can use a closure-based custom validation rule directly in your console command with command-specific business logic:


public function rules(): array
{
    return [
        'start-date' => [
            'date_format:Y-m-d',
            function (string $attribute, mixed $value, Closure $fail) {
                $date = Carbon::parse($value);
                $startOfYear = Carbon::now()->startOfYear();

                if ($date->lessThan($startOfYear)) {
                    $fail("The {$attribute} must be a date from {$startOfYear->format('Y-m-d')} or later.");
                }
            }
        ],
    ];
}

When validation passes, you know you're working with valid input, and your handle() method can stay clean from manual validation checks.

Another neat use-case using the built-in validation rules is validating that an input exists in the database automatically with the exists rule:

public function rules(): array
{
    return ['user-id' => 'exists:users,id'];
}

Sure, you could easily query a user and conditionally return an error, but I think it's neat that you can validate it using exists automatically and give back a default error message when a record doesn't exist.

You can use this package in your project by installing it via Composer:

composer require cerbero/command-validator

Learn more about this package, get full installation instructions, and view the source code on GitHub.

The post Validate Console Command Input With the Command Validator Package appeared first on Laravel News.

Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.