3

我有一个foobar未内置在 Laravel 中的规则 (),我想在扩展的FormRequest. 如何为该特定规则创建自定义验证器?

public function rules() {
    return [
        'id' => ['required', 'foobar']
    ];
}

我知道Validator::extend存在,但我不想使用外墙。我希望它“内置”到我的FormRequest. 我该怎么做,甚至有可能吗?

4

2 回答 2

6

通过为您的类创建一个validator属性并将其设置为app('validator'). 然后,您可以使用该属性 run extend,就像使用外观一样。

创建一个__construct方法并添加:

public function __construct() {
    $this->validator = app('validator');

    $this->validateFoobar($this->validator);
}

然后创建一个名为的新方法,该方法validateFoobarvalidator属性作为第一个参数并extend在其上运行,就像使用外观一样。

public function validateFoobar($validator) {
    $validator->extend('foobar', function($attribute, $value, $parameters) {
        return ! MyModel::where('foobar', $value)->exists();
    });
}

更多详细信息extend在此处获得。

最后,你FormRequest可能看起来像这样:

<?php namespace App\Http\Requests;

use App\Models\MyModel;
use App\Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest {
    public function __construct() {
        $this->validator = app('validator');

        $this->validateFoobar($this->validator);
    }

    public function rules() {
        return [
            'id' => ['required', 'foobar']
        ];
    }

    public function messages() {
        return [
            'id.required' => 'You have to have an ID.',
            'id.foobar' => 'You have to set the foobar value.'
        ];
    }

    public function authorize() { return true; }

    public function validateFoobar($validator) {
        $validator->extend('foobar', function($attribute, $value, $parameters) {
            return ! MyModel::where('category_id', $value)->exists();
        });
    }
}
于 2014-10-28T18:38:55.607 回答
1

从 5.4 版开始,您可以使用该withValidator方法来扩展规则。

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest
{

    public function rules() {
        return [
            'id' => ['required', 'foobar']
        ];
    }

    public function messages() {
        return [
            'id.required' => 'You have to have an ID.',
            'id.foobar' => 'You have to set the foobar value.'
        ];
    }

    public function withValidator($validator)
    {
        $validator->addExtension('foobar', function ($attribute, $value, $parameters, $validator) {
            return ! MyModel::where('category_id', $value)->exists();
        });
    }
}
于 2021-04-17T10:01:03.513 回答