Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Leff7's avatar
Level 4

Laravel/Eloquent - getting the property from morph to many relationship in a single query

I have tables contents, taxonomies, and taxonomy_types and I have set up their relationship like this:

Content:

public function taxonomies()
{
    return $this->morphToMany('App\Taxonomy', 'taxonomical');
}

Taxonomy:

public function contents()
{
    return $this->morphedByMany('App\Content', 'taxonomical');
}

public function type()
{
    return $this->hasOne('App\TaxonomyType', 'id', 'tt_id');
}

TaxonomyType:

public function taxonomy()
{
    return $this->belongsTo('App\Taxonomy');
}

Now I would like to do a query where I would get a content taxonomy of type category. Now I am able to do this like this:

foreach($content->taxonomies as $taxonomy)
{
   if ($taxonomy->type == 'category'){
     $category = $taxonomy->name;
   }
}

But, I would like to do this eloquent way in a single query, something like this if possible:

$content->taxonomies()->where('type', 'category')->get();

How can I do that?

0 likes
1 reply
tuneless's avatar

Eloquent does not support Eager Loading of Polymorphic Childs as of yet. Eloquent is only able to Eager Load Polymorphic Parents. I would advise you to use the Query Builder instead and do it the raw way.

So I use the query builder for this problem.

Please or to participate in this conversation.