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

Validations

Validation errors return the same format as the error response macro.

WantsJson

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

When validation fails

Laravel's validation feature will return the same format as the response()->error() macro.

PostsController.php
<?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:

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.

This customization is installed in your app\Http\Controller.php under the formatValidationErrors method.