我是Laravel的新手,我尝试验证请求。我必须以下请求类:
namespace App'Http'Requests;
class TestRequest extends FormRequest
{
protected function rules()
{
return [
'group_id' => 'required|exists:groups,id,deleted_at,NULL|exists:group_users,group_id,user_id,' . 'Auth::user()->id
];
}
}
我的问题是:
- 我必须检查该组是否存在并且未被删除。
- 我必须检查当前登录的用户是否是组的一部分。第二个"exists"规则
- 当其中任何一个存在失败时,我如何知道哪一个失败?
- 我想为这些存在检查返回一个不同的错误消息。我该怎么做呢?
- 我必须为此编写自定义验证吗?
PS:我使用Laravel 5.3
我建议编写一个自定义规则。查看下面的链接,了解在代码中的添加位置
https://laravel.com/docs/5.3/validation custom-validation-rules
Validator::extend('group_check', function($attribute, $value, $parameters, $validator) {
// Do custom exists check 1;
$group = Group::where('id', $value)->where('deleted_at', 'null')->first();
if (!$group) {
return false;
}
// Do custom exists check 2;
});
Validator::replacer('group_check', function($message, $value, $parameters, $validator) {
// Do custom exists check 1 but instead of returning false, return a custom message
// Do custom exists check 2 return a custom message
});