cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
778 stars 109 forks source link

Filling morphMany relationships #615

Closed proxymurder closed 3 years ago

proxymurder commented 3 years ago

not really an issue but, currently I have:

Articles (Schema): 'title' => string, 'slug' => string, 'content' => string, 'user_id' => foreignId,

Images (Schema): 'url' => string, 'imageable_id' => string, 'imageable_type' => string, OR morphs(imageable),

Article (Class): user = () => { return $this->belongsTo(User::Class); } images = () => { return $this->morphMany(Image::class, 'imageable'); }

Image (Class): imageable = () => { return $this->morphTo('imageable'); }

and im testing, on php unit; $this->jsonApi()->withData([ 'type' => 'articles', 'attributes' => Article::factory()->raw(), 'relationships' => [ 'users' => [ 'data' => [ 'type' => 'users', 'id' => User::factory()->create()->getRouteKey(), ] ], ], ])->post(route('api.v1.articles.create)); this works; but is there a way to include the images relationship within the same request... because the only thing Im thinking about right now is that the Images table can only be filled via the images routes: $this->jsonApi()->withData([ 'type' => 'images', 'attributes' => Image::factory()->raw(), 'relationships' => [ 'imageable' => [ 'data' => [ 'type' => 'articles', 'id' => Article::factory()->create()->getRouteKey(), ] ], ], ])->post(route('api.v1.images.create));

lindyhopchris commented 3 years ago

Not totally sure what you're asking... but if I've got this correct, the answer is that under the JSON:API spec you'd need to create the images and article as separate requests, e.g. one to POST /api/images and one to POST /api/articles. It would make sense for the second request to associate the two together.

proxymurder commented 3 years ago

ok just wanted someone to confirm...