user3016453 user3016453 - 15 days ago 6
JSON Question

Laravel returning intergers in json response

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.

Answer

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.