cloudcreativity/laravel-json-api

Filling morphMany relationships

proxymurder opened this issue · 2 comments

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));

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.

ok just wanted someone to confirm...