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];
}
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
do this
if ($validator->fails()) {
$error = $validator->errors();
return response()->json([
'staatus' => "Failed",
'error' => $error,
'success' => false,
'message'=>'',
]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With