如何在 Laravel 中添加响应 HTTP 数据?

问题描述 投票:0回答:2

现在为了获取数据,我从控制器调用方法,该方法以 JSON 形式返回数据:

return response()->json([$data]);

我可以添加此响应全局数据吗?并合并这个

$data

例如,我有一个全局

$user
对象,我想在每个 HTTP 响应中放弃该对象,以避免每个方法中出现以下条目:

return response()->json(["data" => $data, "user" => $user]);
php json laravel laravel-5 response
2个回答
13
投票

@rnj 答案的另一种选择是使用中间件。

https://laravel.com/docs/5.4/middleware#global-middleware

这将允许您挂钩请求,而不是使用您稍后可能决定不想要/不需要的辅助函数。

中间件的

handle
方法可能类似于:

public function handle($request, Closure $next)
{
    $response = $next($request);

    $content = json_decode($response->content(), true);

    //Check if the response is JSON
    if (json_last_error() == JSON_ERROR_NONE) {

        $response->setContent(array_merge(
            $content,
            [
                //extra data goes here
            ]
        ));

    }

    return $response;
}

希望这有帮助!


2
投票

创建您自己的 PHP 类或函数,用您自己的数据包装 Laravel 的响应。例如:

function jsonResponse($data)
{
    return response()->json([
        'user' => $user, 
        'data' => $data,
    ]);
}

然后您可以拨打:

return jsonResponse($data);

这只是一个如何保持程序DRY的简单示例。如果您正在创建一个希望扩展和维护的应用程序,请执行类似this的操作。

© www.soinside.com 2019 - 2024. All rights reserved.