Created
November 7, 2019 02:09
-
-
Save fatkulnurk/ab0142c0746e48bbe3248e87dc50bc43 to your computer and use it in GitHub Desktop.
LARAVEL API FORM REQUEST VALIDATION ERRORS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//https://cwhite.me/laravel-api-form-request-validation-errors/ | |
namespace App\Http\Requests; | |
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest; | |
use Illuminate\Http\JsonResponse; | |
abstract class FormRequest extends LaravelFormRequest | |
{ | |
/** | |
* Get the validation rules that apply to the request. | |
* | |
* @return array | |
*/ | |
abstract public function rules(); | |
/** | |
* Get the failed validation response for the request. | |
* | |
* @param array $errors | |
* @return JsonResponse | |
*/ | |
public function response(array $errors) | |
{ | |
$transformed = []; | |
foreach ($errors as $field => $message) { | |
$transformed[] = [ | |
'field' => $field, | |
'message' => $message[0] | |
]; | |
} | |
return response()->json([ | |
'errors' => $transformed | |
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY); | |
} | |
} | |
/** | |
Output | |
{ | |
"errors": [ | |
{ | |
"field": "username", | |
"message": "The username field is required." | |
}, | |
{ | |
"field": "password", | |
"message": "The password field is required." | |
} | |
] | |
} | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment