Home > Blockchain >  How to add or customize response from laravel validation
How to add or customize response from laravel validation

Time:07-22

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];
}

CodePudding user response:

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);
    }

CodePudding user response:

do this

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