Black Mamba
Black Mamba

Reputation: 15545

How to customize JSON format of error in validation in Lumen(Laravel)

I am sending error messages like this in case of errors in getting data from DB or any other issue:

return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=>'You have not registered yet.' ], 401);

This gives me a JSON which has everything defined so I easily show the message whatever the problem is.

But in case of error in case of validation, I don't seem to have the power to change the format of the error response JSON.

   $this->validate($request, [
    'email' => 'required',
    'password' => 'required'
    ]);

I want to customize the error format as the one given above so that I don't have to change my error showing mechanism.

Upvotes: 1

Views: 1837

Answers (1)

Tudor
Tudor

Reputation: 1898

You can manually create a validator and add your custom response if it fails, like this:

$validator = Validator::make($request->all(), [
    'email' => 'required',
    'password' => 'required'
]);

if ($validator->fails()) {
    return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=> $validator->errors()->first() ], 401);
}

Upvotes: 1

Related Questions