Laravel Eloquent API中的camel case,DB中的snake case

tv6aics1  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(133)

有没有一个非常简单的解决方案或软件包,使我所有的模型属性camelCase,同时处理API(请求,响应),但在我的数据库中使用snake_case?我并不真的想对每个属性都使用属性setter/getter,我需要一些不那么麻烦的东西。

yduiuuwa

yduiuuwa1#

很简单
创建App\Http\Middleware\FrontendCase.php并在路由中使用它。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FrontendCase
{

    public const CASE_SNAKE = 'snake';
    public const CASE_CAMEL = 'camel';

    public function handle(Request $request, Closure $next)
    {
        $request->replace(
            $this->convertKeysToCase(
                self::CASE_SNAKE,
                $request->post()
            )
        );
        $response = $next($request);
        if ($response instanceof JsonResponse) {
            $response->setData(
                $this->convertKeysToCase(
                    self::CASE_CAMEL,
                    json_decode($response->content(), true)
                )
            );
        }
        return $response;
    }
    private function convertKeysToCase(string $case, $data)
    {
        if (!is_array($data)) {
            return $data;
        }

        $array = [];

        foreach ($data as $key => $value) {
            $array[Str::{$case}($key)] = is_array($value)
                ? $this->convertKeysToCase($case, $value)
                : $value;
        }

        return $array;

    }
}

相关问题