Skip to content

Commit

Permalink
Merge pull request laravel#41 from eurides-eu/feature/handle-error-co…
Browse files Browse the repository at this point in the history
…des-and-messages

Handle API error codes & messages
  • Loading branch information
jaureguivictoria authored May 9, 2018
2 parents e390eaf + 1053590 commit 3b09eba
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 3b09eba

Please sign in to comment.