Last active
December 8, 2020 18:16
-
-
Save carestad/2d16cad66ffca49c397f979b052e2dc2 to your computer and use it in GitHub Desktop.
[Laravel] Return validation errors as proper object/arrays
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\Http\Requests; | |
use Illuminate\Foundation\Http\FormRequest; | |
class FooRequest extends FormRequest | |
{ | |
public function authorize() | |
{ | |
return true; | |
} | |
public function rules() | |
{ | |
return []; | |
} | |
// This will re-shape the validation errors into proper arrays/objects | |
protected function failedValidation(Validator $validator) | |
{ | |
$validationErrors = $this->validator->errors(); | |
$errors = []; | |
foreach ($validationErrors->toArray() as $key => $value) { | |
Arr::set($errors, $key, $value); | |
} | |
throw new HttpResponseException(response()->json([ | |
'errors' => $errors, | |
], 422)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment