最“Laravely”的方式,我能想到的,使用形式请求类,像这样:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class PaperFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
// rules here
}
protected function getValidatorInstance()
{
$validator = parent::getValidatorInstance();
$validator->after(function() use ($validator) {
// logic for detecting mismatches goes here
// To add validation-errors, simply do:
$validator->errors()->add(
'colorMistmatch',
'This color does not go with this paper'
);
return $validator;
}
}
}
一旦错误已经被添加到验证,比如,你可以在你的刀片显示它们通过这样做的视图:
@if ($errors->has('colorMistmach'))
{{ $errors->first('colorMistmach') }}
@endif
您可能能够在验证中使用“存在”规则。 http://laravel.com/docs/5.1/validation#rule-exists。但是,我只是简单地创建一个函数,它只是查询数据透视表并检查组合是否有效。 – Dave
您也可以在检查请求后创建验证挂钩以检查条件。检查http://laravel.com/docs/5.1/validation#other-validation-approaches:验证钩后。可能有帮助。 –