我有一个foobar
未内置在 Laravel 中的规则 (),我想在扩展的FormRequest
. 如何为该特定规则创建自定义验证器?
public function rules() {
return [
'id' => ['required', 'foobar']
];
}
我知道Validator::extend
存在,但我不想使用外墙。我希望它“内置”到我的FormRequest
. 我该怎么做,甚至有可能吗?
通过为您的类创建一个validator
属性并将其设置为app('validator')
. 然后,您可以使用该属性 run extend
,就像使用外观一样。
创建一个__construct
方法并添加:
public function __construct() {
$this->validator = app('validator');
$this->validateFoobar($this->validator);
}
然后创建一个名为的新方法,该方法validateFoobar
将validator
属性作为第一个参数并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();
});
}
}
从 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();
});
}
}