Skip to content
Advertisement

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

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.*",

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement