8000 Creating Record With Related Morph One · Issue #503 · cloudcreativity/laravel-json-api · GitHub
[go: up one dir, main page]

Skip to content
Creating Record With Related Morph One #503
Closed
@yoelpc4

Description

@yoelpc4

I have Project model morph one to Document model

app/Models/Project.php

    /**
     * Project morph one contract document
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function contractDocument()
    {
        return $this->morphOne(Document::class, 'documentable');
    }

app/Models/Document.php

    /**
     * Document morph to documentable
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function documentable()
    {
        return $this->morphTo();
    }

with relation registration in adapter

app/JsonApi/v1/Projects/Adapter.php

    /**
     * Project morph one contract document
     *
     * @return \CloudCreativity\LaravelJsonApi\Eloquent\HasOne
     */
    protected function contractDocument()
    {
        return $this->hasOne();
    }

When creating project via [POST] https://api.test/v1/projects with payload

{
    "data": {
        "type": "projects",
        "attributes": {
            "name": "1st project",
        },
        "relationships": {
            "contractDocument": {
                "data": {
                    "type": "documents",
                    "id": "90"
                }
            }
        }
    }
}

I got an internal server error (500) when creating record with message

JSON API relation HasOne cannot be used for an Eloquent MorphOne relation

/**
* Get the relation from the model.
*
* @param Model $record
* @param string $key
* @return Relation|Builder
*/
protected function getRelation($record, $key)
{
$relation = $record->{$key}();
if (!$relation || !$this->acceptRelation($relation)) {
throw new RuntimeException(sprintf(
'JSON API relation %s cannot be used for an Eloquent %s relation.',
class_basename($this),
class_basename($relation)
));
}
return $relation;
}

Do you have any idea?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0