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

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners