Laravel 5 控制器发送 JSON 整数作为字符串

Laravel 5 controller sending JSON integer as string

在我的开发服务器上,来自 Laravel 5 控制器的 JSON 响应显示了正确类型的数据。

例如

imdb_rating: 7.6
imdb_votes: 6271

但在生产服务器上,JSON 响应以字符串形式发回。

imdb_rating: "7.60"
imdb_votes: "6271"

开发和生产都安装了相同版本的 PHP (5.6.11-1)。

关于可能导致此行为的原因有什么想法吗?

确保使用 MySQL Native Driver,它将支持本机数据类型。

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

MySQL 客户端库将 return 所有字段作为字符串。

另一种解决方案是将 json_encode 选项与 JSON_NUMERIC_CHECK 一起使用。

例如:

return response()->json(["foo" => "bar"], 200, [], JSON_NUMERIC_CHECK);

我刚刚 运行 遇到了同样的问题!对于那些正在寻找更合适的解决方案的人,您可能需要查看 $casts 属性 for Eloquent 模型。

接受的解决方案会起作用,但它也会转换您可能不想转换的字段。我建议将此添加到您的 Eloquent 模型中:

protected $casts = [ 'imdb_rating' => 'float', 'imdb_votes' => 'integer' ];

这将直接在您的模型对象中转换值,因此您无需担心更新多个端点。我希望这对其他人和我一样有帮助!

你可以 return 像

这样类型转换的整数
return (int)Post::find(1)->id;

我认为这也可以帮助简化操作!我正在使用 laravel v9.x.

将函数放在BaseController中:

class Controller extends BaseController {
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public static function json($json) {
        return response()->json($json, 200, [], JSON_NUMERIC_CHECK);
    }

}

现在在您的模型或您使用的任何东西中:

return self::json($all);