plushyObject plushyObject - 2 months ago 20
reST (reStructuredText) Question

Laravel REST API with Polymorphic Relationship with nested JSON

I have 2 models, Games and Images. When I query '/games' in my API, I am returning JSON for all of the Games in the database. How should I query the DB in my GamesController to pass down the Image associated with the Game without explicitly creating an "image_url" column in my Game model? Is that the only way? I would like to nest like this:

{
id: 1,
title: 'Halo 5',
image: {
url: 'http://theimageurlhere.com',
imageable_id: 1,
imageable_type: 'App\Game'
}
}

Answer

In your Games model you need write something like this:

public function images()
{
    return $this->hasMany('App\Images', 'imageable_id', 'id')
        ->whereImageableType('App\Game');
}

And when you take your games:

return Games::select()
        ->with('images')
        ->get();