Skip to content

Instantly share code, notes, and snippets.

@jalallinux
Last active March 5, 2022 10:45
Show Gist options
  • Save jalallinux/ace87fabfffa8d54c0c7a3b31ab7703b to your computer and use it in GitHub Desktop.
Save jalallinux/ace87fabfffa8d54c0c7a3b31ab7703b to your computer and use it in GitHub Desktop.
Laravel: Convert validation rules exception to another exception
<?php
namespace App\Exceptions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* Custom validation exception format
* @param ValidationException $e
* @param Request $request
* @return JsonResponse|Response
* @throws Throwable
*/
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
$this->convertValidationRules($e);
return parent::convertValidationExceptionToResponse($e, $request);
}
/**
* Convert validation rules
* @param ValidationException $exception
* @return void
* @throws Throwable
*/
public function convertValidationRules(ValidationException $exception)
{
collect($exception->validator->failed())->each(function ($failed, $key) {
throw_if(collect($failed)->keys()->contains('Exists'), (new ModelNotFoundException())->setModel($key));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment