Skip to content

Instantly share code, notes, and snippets.

@carestad
Last active Dec 8, 2020
Embed
What would you like to do?
[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