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? (36 h 00 min)

You also get:

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

Already a member? Login here

Ilya Savianok avatar

Are databases with polymorphic relations scalable?

Modestas avatar

Could you explain what you have in mind by that?

Ilya Savianok avatar

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?

Modestas avatar

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.