Last active
October 7, 2018 06:05
-
-
Save JuanDMeGon/6cc604532e5f2b975c9c88a7ee581bec to your computer and use it in GitHub Desktop.
Este es el código completo del middleware que ayuda a resolver el problema de los nombres transformados
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
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Validation\ValidationException; | |
class TransformInput | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next, $transformer) | |
{ | |
$transformedInput = []; | |
foreach ($request->request->all() as $input => $value) { | |
$transformedInput[$transformer::originalAttribute($input)] = $value; | |
} | |
$request->replace($transformedInput); | |
$response = $next($request); | |
if (isset($response->exception) && $response->exception instanceof ValidationException) { | |
$data = $response->getData(); | |
$transformedErrors = []; | |
foreach ($data->error as $field => $error) { | |
$transformedField = $transformer::transformedAttribute($field); | |
$transformedField = str_replace('_', ' ', snake_case($transformedField)); | |
$field = str_replace('_', ' ', snake_case($field)); | |
$transformedErrors[$transformedField] = str_replace($field, $transformedField, $error); | |
} | |
$data->error = $transformedErrors; | |
$response->setData($data); | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment