Laravel 5 控制器将 JSON 整数作为字符串发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31527050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 controller sending JSON integer as string
提问by Muggles
On my development server the JSON response from the Laravel 5 controller shows the data in the correct types.
在我的开发服务器上,来自 Laravel 5 控制器的 JSON 响应以正确的类型显示数据。
e.g
例如
imdb_rating: 7.6
imdb_votes: 6271
But on the production server, the JSON response is sent back as strings.
但在生产服务器上,JSON 响应以字符串形式发回。
imdb_rating: "7.60"
imdb_votes: "6271"
Both development and production have the same version of PHP installed (5.6.11-1).
开发和生产都安装了相同版本的 PHP (5.6.11-1)。
Any ideas on what may be causing this behaviour?
关于可能导致这种行为的任何想法?
回答by David R. Myers
I just ran into this same issue! For those of you looking for a more appropriate solution, you might want to check out the $casts
property for Eloquent models.
我刚刚遇到了同样的问题!对于那些正在寻找更合适的解决方案的人,您可能需要查看$casts
Eloquent 模型的属性。
The accepted solution will work, but it will also convert fields that you may not want converted. I would recommend adding this to your Eloquent model:
接受的解决方案将起作用,但它也会转换您可能不想转换的字段。我建议将其添加到您的 Eloquent 模型中:
protected $casts = [ 'imdb_rating' => 'float', 'imdb_votes' => 'integer' ];
This will convert the values directly in your model object, so you won't need to worry about updating multiple endpoints. I hope this helps others as it did me!
这将直接转换模型对象中的值,因此您无需担心更新多个端点。我希望这对其他人有帮助,就像对我一样!
回答by DavidDomain
Make sure to use MySQL Native Driverwhich will support native data types.
确保使用支持本机数据类型的MySQL 本机驱动程序。
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.
如果使用 mysqlnd 库,可以通过设置 MYSQLI_OPT_INT_AND_FLOAT_NATIVE 连接选项将整数和浮点列转换回 PHP 数字。如果设置,mysqlnd 库将检查结果集元数据列类型并将数字 SQL 列转换为 PHP 数字,如果 PHP 数据类型值范围允许的话。这样,例如,SQL INT 列将作为整数返回。
MySQL Client Library will return all fields as strings.
MySQL 客户端库将所有字段作为字符串返回。
Another solution would be to use json_encode options with JSON_NUMERIC_CHECK
.
另一种解决方案是将 json_encode 选项与JSON_NUMERIC_CHECK
.
For example:
例如:
return response()->json(["foo" => "bar"], 200, [], JSON_NUMERIC_CHECK);
回答by MH Fuad
you can return the integer with typecasting like
您可以使用类型转换返回整数,例如
return (int)Post::find(1)->id;