Last active
March 5, 2022 10:45
-
-
Save jalallinux/ace87fabfffa8d54c0c7a3b31ab7703b to your computer and use it in GitHub Desktop.
Laravel: Convert validation rules exception to another exception
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 | |
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