【Laravel11】Command Validatorパッケージ

Laravel

Laravel News で紹介されていましたが、Console CommandでLaravelのValidatorを自動適用させるパッケージ Command Validator を使ってみました。

Just a moment...
GitHub - cerbero90/command-validator: ✅ Laravel package to validate the input of console commands.
✅ Laravel package to validate the input of console commands. - cerbero90/command-validator

前提条件

  • Laravel11を使っていきます
  • PHP8.2以降(Laravel11の対応バージョン)
  • Composerインストール済
  • Ubuntuで作業していきます

Command Validatorの概要

LaravelのArtisan Consoleコマンドの入力にValidatorを適用するためのTraitです。

利点としては、

  • 「rules()」を設置すれば入力に対しValidatorを適用してくれる
  • Validatorの判定結果のハンドリング実装が不要
  • Validator通過後の入力値が「handle()」に渡される

といったところでしょうか。

▼実装のイメージ

use Cerbero\CommandValidator\ValidatesInput;

class Sample extends Command
{
    use ValidatesInput;

    protected $signature = 'app:sample {--start-date=}';

    // ...

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

▼実行例

これからやること

  • Laravel新規プロジェクト作成
  • Command Validatorインストール
  • Artisanコマンド作成
  • Artisanコマンド実行

Laravel新規プロジェクト作成

新規プロジェクト「command-validator」を作成します。

composer create-project laravel/laravel:^11 command-validator

Command Validator インストール

プロジェクトフォルダに入ってから Command Validatorをインストールします。

cd command-validator
composer require cerbero/command-validator

Artisanコマンド作成

Artisanコマンド「app:sample」を作成します。

php artisan make:command Sample

「app/Console/Commands/Sample.php」が作成されるので

開いて編集します。

<?php

namespace App\Console\Commands;

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

class Sample extends Command
{
    use ValidatesInput;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:sample {--start-date=}';

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        var_dump($this->option('start-date'));
    }

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

Artisanコマンド実行

では、上記で作成したArtisanコマンド「app:sample」を実行してみます。

まずは、Validatorルールに反する例から

php artisan app:sample --start-date=2024/09/24

「Y-m-d」の日付フォーマットに合致しないので叱られました。

では、Validatorルールに適合する例を

php artisan app:sample --start-date=2024-09-24

バリデーションをパスした入力が出力されました。

以上です。

  • 0
  • 0
  • 0
  • 0

コメント

タイトルとURLをコピーしました