Skip to content

Commit

Permalink
Fix serialization for MorphTo relationships (#97)
Browse files Browse the repository at this point in the history
* feat: `MorphTo` serialization

* Run Prettier

* chore: use `createModelByType`

* Remove unnecessary line

---------

Co-authored-by: SychO9 <[email protected]>
Co-authored-by: Toby Zerner <[email protected]>
  • Loading branch information
3 people authored Mar 31, 2024
1 parent 21248fd commit 4c3b44f
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Laravel/EloquentResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Str;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Pagination\OffsetPagination;
Expand Down Expand Up @@ -76,7 +77,13 @@ protected function getRelationshipValue(Model $model, Relationship $field, Conte
// related model with the value of the ID filled.
if ($relation instanceof BelongsTo && $context->include === null) {
if ($key = $model->getAttribute($relation->getForeignKeyName())) {
$related = $relation->getRelated();
if ($relation instanceof MorphTo) {
$morphType = $model->{$relation->getMorphType()};
$related = $relation->createModelByType($morphType);
} else {
$related = $relation->getRelated();
}

return $related->newInstance()->forceFill([$related->getKeyName() => $key]);
}

Expand Down

0 comments on commit 4c3b44f

Please sign in to comment.