douxian5076 2016-11-23 08:03
浏览 265
已采纳

Laravel在json响应中返回整数

i am using

$user = User::find($user_id);
return response()->json(array('user'=>$user),200);

On local server with php5.9 it returns all the keys except id as string.

{
    "success": "1",
    "message": "success",
    "user": {
        "id": 75,
        "name": "",
        "postal_code": "73733",
    }
}

But the same code on production server with php7.0 returns other keys as of type integer ex. check this postal_code value.

{
    "success": "1",
    "message": "success",
    "user": {
        "id": 75,
        "name": "",
        "postal_code": 73733,
    }
}

So solve this i am using $cast=[] in User.php.

But i have used raw queries also. What is the best way to convert all the values in response json to be of string type.

  • 写回答

3条回答 默认 最新

  • dongnaoxia0927 2016-11-23 08:42
    关注

    The difference in the type is most likely due to the fact that your local server is using the php5-mysqld (non-native) driver, whereas your production server is probably using the php-mysqlnd (native) driver. One of the main differences is that the non-native driver reads all fields as strings, whereas the native driver will automatically convert integer fields to PHP integers.

    The id shows up as an integer in both cases because Laravel automatically adds the primary key field ('id') to the casts array with the type defined by the $keyType property (default to int).

    I would say you have four options:

    1. Attempt to install the non-native mysql driver for PHP 7 on your production server (not recommended).

    2. Don't do anything on the PHP side, and just make sure that whatever is consuming the json can handle strings or integers (probably a good idea either way, but still doesn't solve the real issue).

    3. Add postal_code to your casts array, to ensure it is always casted to a string (not bad; this will work for most cases, but is not exactly the correct solution).

    4. Change the field type of the postal_code field from an integer to a varchar(5), varchar(9), or varchar(10), depending on if you're going to store the +4, and with or without a hyphen (best solution).

    Changing the postal_code data type in the database to a varchar really is the best option. The main reason is that, while they are comprised of numbers, postal codes are not actually integers, or numeric in nature. You will never be doing any arithmetic with them. Additionally, there are postal codes that start with a leading 0, and if the value is stored as an integer, this is an extra edge case condition you have to contend with whenever displaying postal codes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型