How to set custom response for selected Request class in Laravel 5.5

eithed picture eithed · Oct 10, 2017 · Viewed 10.6k times · Source

I'm trying to use Laravel validation to generate custom error message, however I'm unable to find the function I should be overriding.

Route: POST:/entries/ uses EntryController@store which uses EntryStoreRequest to perform validation.

EntryStoreRequest

namespace App\Api\V1\Requests;

class EntryStoreRequest extends ApiRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'message' => [
                'string',
                'required',
                'max:65535',
            ],
            'code' => [
                'string',
                'max:255',
                'nullable'
            ],
            'file' => [
                'string',
                'max:255',
                'nullable'
            ],
            'line' => [
                'string',
                'max:255',
                'nullable'
            ],
            'stack' => [
                'string',
                'max:65535',
                'nullable'
            ]
        ];
    }
}

ApiRequest

namespace App\Api\V1\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class ApiRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

The errors are currently returned as:

{
    "message": "The given data was invalid.",
    "errors": {
        "message": [
            "The message field is required."
        ]
    }
}

I want to format them as:

{
    "data": [],
    "meta: {
        "message": "The given data was invalid.",
        "errors": {
            "message": [
                "The message field is required."
            ]
        }
}

How can I achieve this within the ApiRequest class?

Answer

Marcin Nabiałek picture Marcin Nabiałek · Oct 10, 2017

If you want to customize validation response only for selected Request class, you need to add failedValidation() message to this class:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $response = new JsonResponse(['data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $validator->errors()
             ]], 422);

    throw new \Illuminate\Validation\ValidationException($validator, $response);
}

This way you don't need to change anything in Handler and have this custom response only for this single class.

And if you want to change format globally for all responses you should add to app\Exceptions\Handler.php file the following method:

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
             'data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $exception->errors()
             ]
             ], $exception->status);
}

You can read about this also in Upgrade guide in Exception Format section