Skip to content

Instantly share code, notes, and snippets.

@JuanDMeGon
Created July 13, 2017 17:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JuanDMeGon/2fa0a767a0bddcadf55a0a6c994cd7d3 to your computer and use it in GitHub Desktop.
Save JuanDMeGon/2fa0a767a0bddcadf55a0a6c994cd7d3 to your computer and use it in GitHub Desktop.
This is the modification of middleware to Transform file inputs too
<?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 = [];
$allFields = $request->all();
$queryParams = $request->query();
$transformableFields = array_diff($allFields, $queryParams);
foreach ($transformableFields 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);
$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