Reputation: 4783
Can I override some property in validation request to control what happens if validation fails? (I don't want to use validation in controller)
I have user validation request:
public function rules()
{
return [
'email' => 'required|email|max:255|unique:user',
'name' => 'required',
'password' => 'required|min:6',
'password_confirmation' => 'required|min:6|same:password'
];
}
And when AJAX call is made to register method this happens:
public function postRegisterAjax(UserRegistrationValidationRequest $request)
{
...
return $this->responseJson($status, $msg);
}
I need to update $msg
somehow so that I can return the validation error message dynamically through JS.
EDIT: my final solution (in my custom form request)
public function failedValidation(Validator $validator)
{
if ($validator->fails()) {
$status = Status::ERROR;
throw new HttpResponseException(response()->json(["response" => [
'msg' => $validator->errors()->all(':message'),
'status' => $status
]]));
}
return response()->json(["response" => [
'msg' => 'User successfully registered',
'status' => Status::SUCCESS
]]);
}
Upvotes: 2
Views: 1514
Reputation: 2070
To return the validation error message:
In Laravel Form Request Validation, if validation fails, in the case of an AJAX request, a JSON response will be returned. The JSON response holds all validation errors. You can access them in your ajax
error response.
(dump your error response, you can see them in responseJSON
).
If you would like to add additional logic/validation and append errors to your error bag
, you can use after-validation-hook.
Hope it will help you..
UPDATE
You can override the laravel form request
's response method like the follwing,
public function response(array $errors)
{
return response()->json(['status' => $status, "response" => $errors]);
}
in your response you would be able to access the errors as data.response
Upvotes: 1
Reputation: 4815
Updated:
public function postRegisterAjax(UserRegistrationValidationRequest $request)
{
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
$msg = $validator->errors();
return $this->responseJson($status, $msg);
}
}
Upvotes: 0