Skip to main content

Polymorphic Many-to-Many: "Trick" To Query Data

Premium
3 min read

In Laravel's many-to-many polymorphic relations, there is a situation where you can't get ALL records of different models by their "parent" record. Let me explain, and show the potential solution.

Scenario: you have multiple Models that each may have multiple tags.

Example Tags: "eloquent", "vue", "livewire"

And then each Post, Video, and Course may have many tags.

Our Task: get all records (Posts + Videos + Courses) by a specific tag.

Unfortunately, there's nothing like $tag->taggables()->get(). You will see the solution for this below, but...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 41 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

IS
Ilya Savianok ✓ Link copied!

Are databases with polymorphic relations scalable?

M
Modestas ✓ Link copied!

Could you explain what you have in mind by that?

IS
Ilya Savianok ✓ Link copied!

I mean what disadvandages of polymorphic relations can expect me apart from inability to control data through SQL, possible data inconsistence and orphan entries? What if I decide to shard my database in the future, will it be hard to deal with this kind of relationships?

M
Modestas ✓ Link copied!

So that's a bit more complicated than we are comfortable suggesting you.

But generally, you will have orphans in your database if you don't manage/handle it correctly yourself. As for sharding - you might encounter some issues, but not a lot. As long as database/laravel knows where to point for specific records you might be okay.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.