How to add or customize response from laravel validation

Viewed 41

I've searched over the internet to find answer for my issue but could not find it. Please see details below.

What response I currently have

{
    "message": "The expected salary field is required.",
    "errors": {
        "expected_salary": [
            "The expected salary field is required."
        ]
    }
}

What I need:

{
    "status": "FAILED",
    "message": "The expected salary field is required.",
    "errors": {
        "expected_salary": [
            "The expected salary field is required."
        ]
    }
}

Validation Rules:

public function rules()
{
    return ['expected_salary' => 'required];
}
3 Answers

do this

if ($validator->fails()) {
  $error = $validator->errors();
   return response()->json([
            'staatus' => "Failed",
            'error' => $error,
            'success' => false,
            'message'=>'',
        ]); 
}

You can edit your invalid response data globally in app/Exceptions/Handler.php.

It overrides from vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php.

Below is my examples...

protected function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            'code' => $exception->status,
            'message' => collect($exception->errors())->first(),
            'data' => [
                'errors' => $exception->errors(),
                'exception' => in_array(config('app.env'), ['local', 'dev']) ? $this->convertExceptionToArray($exception) : [],
                'request' => $request->all()
            ]
        ], $exception->status);
    }

By overriding the failedValidation method, you can flexibly customize the validation error response for a specific FormRequest.

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\HttpFoundation\Response;

class FooBarRequest extends FormRequest
{
    // your other code ...

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        throw (new HttpResponseException(response([
            'status' => 'FAILED',
            'message' => $validator->errors()->first(),
            'errors' => $validator->errors()->toArray(),
        ]), Response::HTTP_UNPROCESSABLE_ENTITY));
    }
}

Further reading: https://laracasts.com/discuss/channels/laravel/how-make-a-custom-formrequest-error-response-in-laravel-55

Related