This project has been archived. If you're curious, check out one of my latest courses:
If you work with JavaScript, check out the fetch use cases and JavaScript projects.
Thank you! — Jad Joubran
If you test validations errors in your brower, you will most likely get a redirection.
That's because internally, Laravel makes use of the wantsJson
method and only serves Json if you request a Json response.
In order to request a Json response, you have to set the following header:
Accept: application/json
Laravel's validation feature will return the same format as the response()->error()
macro.
<?php
class PostsController
{
public function update(Request $request)
{
$this->validate($request, [
'title' => 'required',
'url' => 'required|url',
]);
...
}
}
If this validation fails, you will get the following response:
{
"message":"422 error",
"errors":{
"message":"The title field is required.",
"info":["title"]
},
"status_code":422
}
✅ You can directly use the errors.message
in your front-end.
✅ You can access the field for which the validation failed under errors.info[0]
.
✅ Only the first validation error will be returned, even if more than one have failed.