Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fatkulnurk/ab0142c0746e48bbe3248e87dc50bc43 to your computer and use it in GitHub Desktop.
Save fatkulnurk/ab0142c0746e48bbe3248e87dc50bc43 to your computer and use it in GitHub Desktop.
LARAVEL API FORM REQUEST VALIDATION ERRORS
<?php
//https://cwhite.me/laravel-api-form-request-validation-errors/
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
use Illuminate\Http\JsonResponse;
abstract class FormRequest extends LaravelFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
abstract public function rules();
/**
* Get the failed validation response for the request.
*
* @param array $errors
* @return JsonResponse
*/
public function response(array $errors)
{
$transformed = [];
foreach ($errors as $field => $message) {
$transformed[] = [
'field' => $field,
'message' => $message[0]
];
}
return response()->json([
'errors' => $transformed
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
}
}
/**
Output
{
"errors": [
{
"field": "username",
"message": "The username field is required."
},
{
"field": "password",
"message": "The password field is required."
}
]
}
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment