3

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
  • 1
    Have you tried casting them to int? laravel.com/docs/5.2/eloquent-mutators#attribute-casting Commented Apr 1, 2020 at 8:21
  • I don't understand why I need to cast if it's already int in the DB. Commented Apr 1, 2020 at 8:29
  • Maybe because Laravel doesn't take the DB column type into consideration? Commented Apr 1, 2020 at 8:38

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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

1 Comment

Ii doesn't. This problem happens on Homestead (tried on Homestead 10.1.1) which by default comes with mysqlnd enabled. The problem is still there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.