我有2个函数使用这样的一个验证器
public function store( Request $request ) {
$validate = $this->validator( $request );
if ( $validate->fails() ) {
return response()->json( [ 'errors' => $validate->errors() ] );
}
}
public function update( Request $request, $id ) {
$validate = $this->validator( $request, $id );
if ( $validate->fails() ) {
return response()->json( [ 'errors' => $validate->errors() ] );
}
}
private function validator( Request $request, $id = "" ) {
$validator = Validator::make( $request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $id,
'password' => 'required|min:6|confirmed',
'password_confirmation' => "required",
'role' => "required"
] );
if ( $validate->fails() ) {
return response()->json( [ 'errors' => $validate->errors() ] );
}
return $validator;
}
在这个if验证器中,它返回响应给验证器函数而不是父函数。 我想编写函数验证器来检查并给父返回响应,因为我不想检查并一次又一次返回
答案 0 :(得分:1)
您可以创建一个继承Request
并验证其输入的类。
在控制器方面,您只有:
public function store(SomeRequestValidation $request ) {
//Do something because it has been validated in SomeRequestValidation
}
public function update(SomeRequestValidation $request) {
//Do something because it has been validated in SomeRequestValidation
}
注意:如果是Laravel,那么我们在谈论FormRequests
https://laravel.com/docs/5.6/validation#creating-form-requests
编辑:一个有关重写请求功能可以完成的小示例。
public function authorize(Request $request)
{
if (/*something*/) {
return true;
}
return false;
}
public function forbiddenResponse()
{
return json_encode("Oh no you don't");
//return response()->view('errors.403');
}
https://laravel.com/api/5.6/Illuminate/Foundation/Http/FormRequest.html
答案 1 :(得分:-1)
您可以抛出将直接给出响应的错误,现在无需在函数中一次又一次地返回
throw new HttpResponseException(response()->json($error, 422, $headers));
我认为这会对您有所帮助。