Created
July 20, 2020 06:52
-
-
Save nimaamiri92/0d0112204927942e568d8d583cc99913 to your computer and use it in GitHub Desktop.
Throw error with Laravel validation error format
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 {YOUR_NAMESPACE}; | |
use Illuminate\Validation\ValidationException; | |
class CustomValidationError | |
{ | |
private $errors = []; | |
public function setError(string $field, $fieldError) | |
{ | |
if(is_array($fieldError)){ | |
foreach ($fieldError as $key => $error){ | |
$this->errors[$key][$field] = $error; | |
} | |
}else{ | |
$this->errors[$field] = [$fieldError]; | |
} | |
return $this; | |
} | |
public function getErrors() | |
{ | |
return $this->errors; | |
} | |
public function throwErrors() | |
{ | |
$error = ValidationException::withMessages($this->getErrors()); | |
throw $error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
> USAGE:
Suppose you are middle of controller or repository file and you want check if
$isChecked
hasTRUE
value or not, and if has false value you want throw error:In controller or repository file:
return (new CustomValidationError)->setError('isChecked','HERE_TYPE_YOUR_ERROR_MESSAGE')->throwErrors();
return (new CustomValidationError)->setError('isChecked','HERE_TYPE_YOUR_ERROR_MESSAGE')->('isChecked','HERE_TYPE_YOUR_ERROR_MESSAGE2') ->throwErrors();