Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ynoth25's avatar

Laravel API validation error response

I have this Laravel 9 API project and I can now return response whenever I inserted/updated successfully. But when it comes to validation in which I used FormRequest a separate file to validate inputs. My question is is there a "proper/safe way" to return validation errors as a json response?

0 likes
5 replies
ynoth25's avatar

I dont catch it @forster69, I used FormRequest to validate it, my question is how to return that messages as a json response for my API

frankielee's avatar

@ynoth25

{
	"accept"=>"application/json"
}

I think the simplest way would be adding the header to every request you sent.

mehdi0121's avatar

as @frankielee said just set Accept in your header and if you want to customize the validation error use ValidationException in Exceptions->Handler.php

        //Validation errors
        if($exception instanceof ValidationException and $request->expectsJson()){
            return response([
                'data'=>[
                    'message'=>'text',
                    'errors'=>$exception->validator->getMessageBag()
                ]
            ],Response::HTTP_UNPROCESSABLE_ENTITY);
        }
1 like
ynoth25's avatar

Guys! thank you for your help! I solved it by modifying Exception/Handler.php error rendering. Got to solve 1 last problem, it seems like I cant catch & modify Internal Server Error ( 500xx) status code response.

Is there anyway to do this or

Please or to participate in this conversation.