Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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.*",
like image 235
TheUnreal Avatar asked Dec 09 '25 21:12

TheUnreal


1 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.

like image 101
Wotta Avatar answered Dec 12 '25 10:12

Wotta