Skip to content

Instantly share code, notes, and snippets.

@carestad
Last active December 8, 2020 18:16
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 carestad/2d16cad66ffca49c397f979b052e2dc2 to your computer and use it in GitHub Desktop.
Save carestad/2d16cad66ffca49c397f979b052e2dc2 to your computer and use it in GitHub Desktop.
[Laravel] Return validation errors as proper object/arrays
<?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