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 let's go step-by-step.
Here's the DB schema for this:
tags
id - integer
name - string
...
posts
id - integer
post_title - string
...
videos
id - integer
video_title - string
...
courses
id - integer
course_title - string
...
taggables
tag_id - `foreignId('tags')->constrained()`
taggable_id - integer (ID of post or video or course)
taggable_type - string (Model name, like "App\Models\Post")
The DB table taggables deserves its migration to be shown, it looks like this:
Then, in the Eloquent Models, you have this code.
app/Models/Post.php
Similarly, the Models of Course
and Video
will have the same identical tags()
method with morphToMany()
.
And then, if needed, the Tag model has multiple morphedByMany()
relations.
app/Models/Tag.php
Now, how to query data. How to get the entries by Tag?
Unfortunately, there's no way to run a single query, like $tag->taggables()->get();
, because there's no single Model structure for different Post/Video/Course, they all have different fields, so how you can group them together?
Well, the trick is to run three different queries, but then combine the results into an identical structure and merge them together into one Collection. From there, you can paginate or transform that collection however you want.
This code will return this structure, if there is a Post/Video for the tag but no Course: