laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
541 stars 41 forks source link

Question - Creating a Related Model and Establishing Relationship #262

Closed MatthiasvanPijkeren closed 7 months ago

MatthiasvanPijkeren commented 11 months ago

Hello,

I'm currently working on a project and I'm trying to figure out the best way to create a related model and establish its relationship with an existing model in a single request. Specifically, I want to create a new CartLine that belongs to a Cart.

Here are the key questions I have:

  1. How do you create a related model (e.g., CartLine) and associate it with an existing model (e.g., Cart) in a single request?

  2. What is the recommended endpoint to use for this operation? Should it be /carts/{id}/cart-lines or /cart-lines?

  3. Could you provide an example of how the request body should be structured for this operation?

Any guidance or examples you can provide would be greatly appreciated. Thank you in advance for your assistance!

Thanks in advance! Matthias

lindyhopchris commented 11 months ago

Hi. I'd recommend you do the tutorial, because the tutorial covers this topic. https://laraveljsonapi.io/docs/3.0/tutorial/

  1. Use the relationships member of the CartLine to associate it to a Cart.
  2. For this scenario /cart-lines will work...
  3. If you use the following:
{
  "data": {
    "type": "cart-lines",
    "attributes": {
      "foo": "bar"
    },
    "relationships": {
      "cart": {
        "data": {
          "type": "carts",
          "id": "456"
        }
      }
    }
  }
}

This should give you enough to go on. The tutorial is there and I'd recommend it as it introduces you to the JSON:API spec (which is what your questions are about) as well as this package.

Also, you might find joining the Slack community a better place to ask questions.

lindyhopchris commented 7 months ago

Closing as I think this has been answered.