Search code examples
phplaraveleloquentrelationshipeager-loading

Laravel: Dynamic Relationship in Model


I have a relationship on my Content model which is meant to be dynamic. I'm using content model as my post types, and each of them in database has a model value that redirects to a model which are the actual contents of the content type, that might be installed later using composer packages.

public function contents() {
        return $this->hasMany($this->model);
    }

It works when I use this relationship in my view

$type->contents

but when I want to eagerload this relationship in my controller;

$types = Content::with('contents')->get();

I get the error

FatalThrowableError in Model.php line 844: Class name must be a valid object or a string

I am yet to figure out why this isn't working or think of alternatives how I can achieve the same thing. I can provide more details if this is not clear. Thanks in advance!

UPDATE (temporary/permanent solution I came up with) I removed the relationships and replaced it with this;

public function getContentsAttribute() {
         $items = $this->contents_type::with('user')->get();
         return $items;
    }

Solution

  • (temporary/permanent solution I came up with) I removed the relationships and replaced it with this;

    public function getContentsAttribute() {
             $items = $this->contents_type::with('user')->get();
             return $items;
        }