Replies: 2 comments
-
@maukoese interesting! Would you mind sharing your implementation of this feature (camel casing the response)? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Hello @romalytvynenko I'm sorry I missed this. I thought I had responded. // app/Http/Middleware/ConvertRequestFieldsToSnakeCase.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
class ConvertRequestFieldsToSnakeCase
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$replaced = [];
foreach ($request->all() as $key => $value) {
$replaced[Str::snake($key)] = $value;
}
$request->replace($replaced);
return $next($request);
}
} // app/Http/Middleware/ConvertResponseFieldsToCamelCase.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
class ConvertResponseFieldsToCamelCase
{
function convertToCamelCase($array)
{
$finalArray = array();
foreach ($array as $key => $value):
if (strpos($key, "_"))
$key = lcfirst(str_replace("_", "", ucwords($key, "_"))); //let's convert key into camelCase
if (!is_array($value))
$finalArray[$key] = $value;
else
$finalArray[$key] = $this->convertToCamelCase($value);
endforeach;
return $finalArray;
}
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$content = $response->getContent();
try {
$json = json_decode($content, true);
$replaced = [];
foreach ($json as $key => $value) {
$replaced[Str::camel($key)] = is_array($value) ? $this->convertToCamelCase($value) : $value;
}
$response->setContent(json_encode($replaced));
}
catch (\Exception $e) {
// you can log an error here if you want
}
return $response;
}
} Of course, they are both registered in // ... rest of code
->withMiddleware(function (Middleware $middleware) {
// ... rest of code
$middleware->api(append: [
\App\Http\Middleware\ConvertRequestFieldsToSnakeCase::class,
\App\Http\Middleware\ConvertResponseFieldsToCamelCase::class,
]);
})
// ... rest of code |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
While setting up API docs for a mobile app frontennd, I'm using custom API resources and a middleware [to convert requests to snake_case and responses to camelCase] and this works fine, but I wish I could cast the metadata to camelcase as well.
Anyone have an idea how this can be achieved? You can see the data part is already camelCase.
Beta Was this translation helpful? Give feedback.
All reactions