Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save marcorivm/71e68fdd469eaee2044b63d3745f2491 to your computer and use it in GitHub Desktop.

Select an option

Save marcorivm/71e68fdd469eaee2044b63d3745f2491 to your computer and use it in GitHub Desktop.
Based on https://github.com/flugger/laravel-responder these middlewares can be included with any laravel controller to convert response values from camelCase which is usually the standard on js clients and snake_case preferred on PHP
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
/**
* A middleware class responsible for converting incoming parameter keys to camel case.
*
* @package flugger/laravel-responder
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
class ConvertToCamelCase
{
/**
* A list of attributes that shouldn't be converted.
*
* @var array
*/
protected $except = [
//
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$data = $this->clean($response->getData());
$response->setData($data);
return $response;
}
/**
* Clean the data in the given array.
*
* @param array $data
* @return array
*/
protected function clean($data)
{
$parameters = [];
foreach ($data as $key => $value) {
$parameters[in_array($key, $this->except) ? $key : camel_case($key)] = (is_object($value) || is_array($value))? $this->clean($value) : $value;
}
return $parameters;
}
}
<?php namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TransformsRequest;
/**
* A middleware class responsible for converting incoming parameter keys to snake case.
*
* @package flugger/laravel-responder
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
class ConvertToSnakeCase extends TransformsRequest
{
/**
* A list of attributes that shouldn't be converted.
*
* @var array
*/
protected $except = [
//
];
/**
* Clean the data in the given array.
*
* @param array $data
* @return array
*/
protected function cleanArray(array $data)
{
$parameters = [];
foreach ($data as $key => $value) {
$parameters[in_array($key, $this->except) ? $key : snake_case($key)] = (is_object($value) || is_array($value))? $this->clean($value) : $value;
}
return $parameters;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment