Created
July 16, 2019 10:57
-
-
Save rodurma/772bac851d73c6455230c2431f9400b6 to your computer and use it in GitHub Desktop.
Customize errors
This file contains 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 | |
namespace App\Http\Requests\Traits; | |
use Illuminate\Http\JsonResponse; | |
use Illuminate\Http\Exceptions\HttpResponseException; | |
use Illuminate\Contracts\Validation\Validator; | |
use Illuminate\Validation\ValidationException; | |
trait FailedValidationTrait | |
{ | |
/** | |
* Handle a failed validation attempt. | |
* | |
* @param \Illuminate\Contracts\Validation\Validator $validator | |
* @return void | |
* | |
* @throws \Illuminate\Validation\ValidationException | |
*/ | |
protected function failedValidation(Validator $validator) | |
{ | |
$response = [ | |
'invalid_fields' => [] | |
]; | |
$errors = (new ValidationException($validator))->errors(); | |
foreach($errors as $field => $error){ | |
$response['invalid_fields'][$field] = $error[0]; | |
} | |
throw new HttpResponseException(response()->json($response, JsonResponse::HTTP_UNPROCESSABLE_ENTITY)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment