laravel does a pretty good job of transparently translating models to json so long as you keep things simple. fortunately, laravel provides an easy way to define a model's json serialization in one method: jsonSerialize().

/** * Define the json format of the model */ public function jsonSerialize():Array { return [ 'id' => $this->id, 'artist' => $this->artist, 'title' => $this->title, 'songs' => $this->songs, // array of songs ]; } // jsonSerialize } Exit fullscreen mode since records contain songs, we want our Record model to include an array of that record's Song models.

we should note that the json format of all those songs is defined by the Song model's own jsonSerialize() method.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners