我想在Laravel控制器上添加自定义验证规则:
所以我写了这个:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}
不幸的是,$validator->errors()
甚至$validator->addMessageBag()
都不起作用。我注意到$validator->fails()
清除了错误消息,添加错误不会使验证失败。
实现此目标的正确方法是什么?
答案 0 :(得分:0)
然后您可以使用after
:
public function update($id, Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|unique:stock.containers|max:255'
]);
$validator->after(function($validator) use($id) {
$container = Container::find($id);
if(!$container)
{
$validator->errors()->add('id', 'Not a valid resource');
}
if($container->owner_id != user_id())
{
$validator->errors()->add('owner_id', 'Not owner of this resource');
}
});
if ($validator->fails()) {
return response()->json($validator->errors(), 422); //i'm not getting any
}
}