Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Laravel API validation responses

I'm building a REST API with Laravel and wondering if there is a way to customize the API responses when validating.

For example, I have a validation rule in a Laravel request, saying a specific field is required.

public function rules() {
   return [
       'title'=>'required|min:4|max:100',
   ];
}

So, for this validation I get the error message in Postman like this

{
    "title": [
        "Please enter Ad Title"
    ]
}

What I want is to customize that response like this..

{
    "success": false,
    "message": "Validation Error"
    "title": [
        "Please enter Ad Title"
    ]
}

So, that the error is more specific and clear.

So, how to achieve this ?

Thanks!

like image 599
Tharindu Thisarasinghe Avatar asked Oct 27 '25 15:10

Tharindu Thisarasinghe


1 Answers

I got a solution for your REST-API Validation Laravel FormRequest Validation Response are change by just write a few lines of code. enter code here

Please add this two-line into your App\Http\Requests\PostRequest.php

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

after that add this function in your file.

you can change $response variable into your specific manner.

protected function failedValidation(Validator $validator) { 
        $response = [
            'status' => false,
            'message' => $validator->errors()->first(),
            'data' => $validator->errors()
        ];
        throw new HttpResponseException(response()->json($response, 200)); 
    }
like image 125
Keyur Patel Avatar answered Oct 29 '25 05:10

Keyur Patel