Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or customize response from laravel validation

Tags:

laravel

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];
}
like image 751
Jie Avatar asked Oct 16 '25 10:10

Jie


2 Answers

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

like image 169
Yusuf T. Avatar answered Oct 19 '25 02:10

Yusuf T.


do this

if ($validator->fails()) {
  $error = $validator->errors();
   return response()->json([
            'staatus' => "Failed",
            'error' => $error,
            'success' => false,
            'message'=>'',
        ]); 
}
like image 23
Sanjog Karki Avatar answered Oct 19 '25 00:10

Sanjog Karki