Skip to content

Commit

Permalink
laravel#39: Handle API error codes & messages
Browse files Browse the repository at this point in the history
  • Loading branch information
jaureguivictoria committed May 8, 2018
1 parent faa5633 commit f058491
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions app/Http/Requests/FormRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

abstract class FormRequest extends LaravelFormRequest
{
/**
* @return mixed
*/
abstract public function rules();

/**
* @param Validator $validator
*
* @return array
*/
protected function formatErrors(Validator $validator)
{
$transformed = [];

$errors = $validator->errors()->getMessages();
$obj = $validator->failed();

foreach ($obj as $input => $rules) {
$i = 0;
$fieldErrors = [];

foreach ($rules as $rule => $ruleInfo) {
$fieldErrors[] = [
'code' => 'errors.'.lcfirst(class_basename($rule)),
'message' => $errors[$input][$i],
];
++$i;
}

$transformed[] = ["$input" => $fieldErrors];
}

return ['errors' => $transformed];
}

/**
* @param Validator $validator
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(
response()->json($this->formatErrors($validator),
JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}
}

0 comments on commit f058491

Please sign in to comment.