Hkm Sadek
Hkm Sadek

Reputation: 3209

How to define the data type before returning JSON data for api backend in laravel

I have developed a api backend to use in mobile. It was all working great before I take the code in another domain for starting deplying. Suddenly I noticed, one of the user_id data type has changed to string where it was int before and all was working.

This is what I am doing in my laravel controller

  $clubs=Club::with(['users' => function($q){
        $q->select('id','profilePic');
    }])->with('leagueCount')
    ->get();

   return response()->json([
        'success' => true,
        'clubs' => $clubs,
    ],200);

And it gives me the result like this

success: true,
clubs: [
{
id: 8,
user_id: "34",  // this shouldn't be a string. It should be int.
 clubName: "PADELCENTER",
 clubDesc: "Testclub",
 color: "#424242",
 logo: "logotouse.png",
 created_at: "2018-05-12 07:44:40",
 updated_at: "2018-05-12 07:44:40",
 users: {
   id: 34,
   profilePic: "20KdcnX5Gb2dSfunwT8JtmBvcVopDmUwKmQ7XeUI.png"
 },
 league_count: [
 {
   id: 31,
   club_id: "8",
   total: "1"
 }
]
},

You can see user_id is a string it should be int

Is there anyways that I forcefully set data type in the model or somewhere?

[Note: user_id is int and unsigned in the database as its a foreign key to user table.]

Many thanks.

Upvotes: 2

Views: 671

Answers (2)

FULL STACK DEV
FULL STACK DEV

Reputation: 15971

There are two ways to solve this

In your model you can cast the output from the database like

$casts = [
'user_id' => 'int'
];

Or you can use Resource php artisan make:resource Club

and after that you u can simply in toArray method

  public function toArray($request)
    {
        return [
            // do casting in here
        ];
    }

Upvotes: 4

thefallen
thefallen

Reputation: 9749

You can cast the property to integer with the Eloquent mutators like this:

class Club extends Model
{
    protected $casts = [
        'user_id' => 'integer',
    ];
}

Upvotes: 4

Related Questions