forked from laravel/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request laravel#41 from eurides-eu/feature/handle-error-co…
…des-and-messages Handle API error codes & messages
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
); | ||
} | ||
} |