Validation 仅当字段为';s零或db中的值
我是拉威尔的新手,很抱歉我的新手问题: 在输入字段中,它必须只有在它为零或者它的值存在于“products”db表中时才有效。 我在Laravel5.2中使用表单请求验证 这是我的代码:Validation 仅当字段为';s零或db中的值,validation,laravel,Validation,Laravel,我是拉威尔的新手,很抱歉我的新手问题: 在输入字段中,它必须只有在它为零或者它的值存在于“products”db表中时才有效。 我在Laravel5.2中使用表单请求验证 这是我的代码: class CreateRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public
class CreateRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'product_id' => 'sometimes|exists:products,id'
];
}
}
这适用于数据库验证,但如果为零,如何使其有效
谢谢你的帮助 这可能会有帮助
public function rules()
{
return [
'product_id' => 'integer|size:0|exists:products,id'
];
}
您必须创建自定义验证规则 如果您使用的是5.6,则可以创建自定义规则或传递闭包
class CreateRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function rules()
{
return [
'product_id' => ['integer', function($attribute, $value, $fail) {
$product = Product::find($value);
if ($value != 0 && !$product ) {
return $fail($attribute.' is invalid.');
}
},
];
}
}
希望这有帮助我建议为此编写一个自定义验证,它很简单: