Laravel - API return fields as string while they are int in the DB

Viewed 624

I have the following code:

$data['daily_missions'] = DailyMission::with(['userProgress' => function($q) use ($user){
            $q->where('user_id',$user->id);
            }])
        ->orderBy('diamonds')
        ->where('is_daily',1)
        ->get();

In the DB, most of the fields of the DailyMission / userProgress models are integers - but the API return them as string.

for example:

{
price: "123"
}

instead of:

{
price: 123
}

Any idea what can cause this issue?

Version:

"laravel/framework": "5.2.*",
3 Answers

In your model, you should define the field as an integer in the $cast attribute.

protected $casts = [
    'field_name' => 'integer',
];

You can read the docs for more information by opening the following documentation link.

Installing and enabling mysqlnd extension can solve this problem. Hope it helps.

mysqlnd extension doesn't solve the issue on it's own. With it also install nd_pdo_mysql extension then it will solve the issue.

Related