laravel 返回值下划线转驼峰

思路:写个middleware把返回值递归转一下

class ResponseTransFormMiddleware
{
    //下划线转驼峰
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        return $this->changeHump(json_decode($response->original,true));
    }


    //转换驼峰(只转key)
    public function changeHump($params)
    {
        if (is_array($params)) {
            foreach ($params as $key=>$value){
                unset($params[$key]);
                $params[$this->convertUnderline($key)] = is_array($value)?$this->changeHump($value):$value;
            }
        }
        return $params;
    }

    public function convertUnderline($str)
    {
        return  preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {return strtoupper($matches[2]);}, $str);
    }
}

middleware注册

$app->routeMiddleware(['responseTransForm' => App\Http\Middleware\ResponseTransFormMiddleware::class,]); //下划线转驼峰

所有的api加一个前缀

$router->group(['prefix' => 'api','middleware'=>'responseTransForm'], function () use ($router) {...});

你可能感兴趣的:(laravel 返回值下划线转驼峰)