Skip to content

Instantly share code, notes, and snippets.

@nimaamiri92
Created July 20, 2020 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nimaamiri92/0d0112204927942e568d8d583cc99913 to your computer and use it in GitHub Desktop.
Save nimaamiri92/0d0112204927942e568d8d583cc99913 to your computer and use it in GitHub Desktop.
Throw error with Laravel validation error format
<?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;
}
}
@nimaamiri92
Copy link
Author

nimaamiri92 commented Jul 20, 2020

> USAGE:

Suppose you are middle of controller or repository file and you want check if $isChecked has TRUE 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();

Response:

{
    "message": "The given data was invalid.",
    "errors": {
        "isChecked": [
            "HERE_TYPE_YOUR_ERROR_MESSAGE"
        ]
    }
}

For throw more error for a field:

return (new CustomValidationError)->setError('isChecked','HERE_TYPE_YOUR_ERROR_MESSAGE')->('isChecked','HERE_TYPE_YOUR_ERROR_MESSAGE2') ->throwErrors();

Response:

{
    "message": "The given data was invalid.",
    "errors": {
        "isChecked": [
            "HERE_TYPE_YOUR_ERROR_MESSAGE"
            "HERE_TYPE_YOUR_ERROR_MESSAGE2"
        ]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment