Skip to content

Instantly share code, notes, and snippets.

@rodurma
Created July 16, 2019 10:57
Show Gist options
  • Save rodurma/772bac851d73c6455230c2431f9400b6 to your computer and use it in GitHub Desktop.
Save rodurma/772bac851d73c6455230c2431f9400b6 to your computer and use it in GitHub Desktop.
Customize errors
<?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