I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :
public function store(CustomFormRequest $request)
{
//
}
I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.
But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:
// Inside my Controller
public function store(CustomFormRequest $request)
{
if ($validator->fails())
{
$errors = $validator->errors();
return response()->json(array('status' => 2, 'msg' => $errors->all() ));
}
}
Could you please help ? Thanks in advance.
The easiest way to do this would be to override the response() method for the form request class.
To do this you can simply add something like the following to your class:
import Illuminate\Http\JsonResponse public function response(array $errors) { if ($this->expectsJson()) { return new JsonResponse(['status' => 2, 'msg' => $errors], 422); } return parent::response($errors); } Don't forget to import Illuminate\Http\JsonResponse
I hope this helps!
I know you want the logic in your controller, but you can still leverage your request file for this. In the Laravel documentation (assuming you're using the latest version) it's described asAdding Post Bindings to Form Requests :
If you want to add an "after" hook to a form request, you can use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:
/** * Configure the validator instance. * * @param \Illuminate\Validation\Validator $validator * @return void */ public function withValidator($validator) { $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); }try this:
form.ajaxSubmit({
async: false,
type: yourMethod,
url: yourRoute,
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
dataType: 'json',
success: function(data){
location.href = data.redirect_to;
},
error: function(data) {
var errors = data.responseJSON;
var errorsArr = [];
for (error in errors) {
errorsArr.push(errors[error]);
}
errorsArr = $.map(errorsArr, function(n){
return n;
});
alert("<strong class='text-danger'>" + errorsArr.join("<br>") + "</strong>");
console.log(errors);
}
});
and in your controller store method make return:
return response()->json(['redirect_to' => '/your_route']);