I think the first one is more common and makes more sense to me because you can clearly understand the relations. However, I'm really confused by the fact that a Brand belongs to a Product (because a brand should have many products). It should be the other way around. Same thing for the relation between Brand and Package. Because normally a Package (or plan) is linked to a product and not a brand., but idk about your business logic, so I might be making wrong assumptions here.
Nov 19, 2022
6
Level 15
What is the recommended approach for designing nested API responses
I have a set of models that have a one on one relationship as defined below. Each of the models has a name attribute
-
Product category -
Productbelongs toProduct category -
Brandbelongs toProduct -
Packagebelongs toBrand -
Metricbelongs toPackage
By this definition, its will mean that any granchild will belong to a (one) grandparent. e.g metric will belong to brand.
When designing the response for a child (e.g metric), what is the best way to return this data and why;
- Option 1 [nested]
[
"name" => "Kilograms",
"package" => [
"name" => "Blue band low fat",
"brand" => [
"name" => '"Blue band",
"product" => [
"name" => "Margarine",
"product_category" => [
"name" => "Spread"
]
]
]
]
]
- Option 2 [flat]
[
"name" => "Kilograms",
"package" => [
"name" => "Blue band low fat"
],
"brand" => [
"name" => '"Blue band"
],
"product" => [
"name" => "Margarine"
],
"product_category" => [
"name" => "Spread"
]
]
Bonus Question: For option 2 (flat), how do you achieve it using Laravel's API Resources
Please or to participate in this conversation.