plushyObject plushyObject - 1 year ago 161
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: '',
imageable_id: 1,
imageable_type: 'App\Game'

Answer Source

In your Games model you need write something like this:

public function images()
    return $this->hasMany('App\Images', 'imageable_id', 'id')

And when you take your games:

return Games::select()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download