Reputation: 743
I have a related REST API question.
I have 2 entities, Product
and Store
, which has a many-to-many
relationship between them. A Product
may be available in 0 or more Store
s and a Store
may have 0 or more Product
s.
But I need a route to add a Product
to a Store
and also a route to remove a Product
from a Store
. The relationship is simple, there is no extra column in the pivot table.
Which approach would you use?
Upvotes: 1
Views: 1808
Reputation: 81
If your Products cannot exist without a Store and must belong to a Store, then it makes sense to nest the route under Stores.
For example:
Add a new Product to a Store
POST /api/store/:id/product/:id
Delete a Product from a Store
DELETE /api/store/:id/product/:id
Either way, it still seems more logical to nest the API routes for adding/deleting products to/from stores, under Store. With this design, the Store is the main focus and you are adding or deleting products from it. It is simple and easy to understand and follow.
Whereas in the alternative design, the Product is the main focus and you are adding stores in which it is being sold in or deleting stores in which it is no longer being sold in. It becomes more complicated than necessary.
Upvotes: 2
Reputation: 59303
If you work for the Product company, and you're keeping track of which stores carry which products, then you would POST to /api/product/{id} to add the store.
If you work for the Store company, which decides which products to carry in which stores, then you would POST to /api/store/{id} to add a product.
Note that I suggest POST, because neither operation is actually creating a product or store.
Upvotes: 0
Reputation: 342
You simply should define in your product store method, that your saved product belongs to chosed stores.
Take a look in Laravel documentation
Upvotes: 0