Laravel Polymorphic Many-To-Many: Get All Related Records

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:

1tags
2 id - integer
3 name - string
4 ...
5
6posts
7 id - integer
8 post_title - string
9 ...
10
11videos
12 id - integer
13 video_title - string
14 ...
15
16courses
17 id - integer
18 course_title - string
19 ...
20
21taggables
22 tag_id - `foreignId('tags')->constrained()`
23 taggable_id - integer (ID of post or video or course)
24 taggable_type - string (Model name, like "App\Models\Post")

The DB table taggables deserves its migration to be shown, it looks like this:

1Schema::create('taggables', function (Blueprint $table) {
2 $table->foreignId('tag_id')->constrained();
3 $table->morphs('taggable');
4});

Here's what the data in that DB table would look like:

Laravel polymorphic many-to-many taggables

Then, in the Eloquent Models, you have this code.

app/Models/Post.php

1class Post extends Model
2{
3 public function tags()
4 {
5 return $this->morphToMany(Tag::class, 'taggable');
6 }
7}

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

1class Tag extends Model
2{
3 public function posts()
4 {
5 return $this->morphedByMany(Post::class, 'taggable');
6 }
7 
8 public function videos()
9 {
10 return $this->morphedByMany(Video::class, 'taggable');
11 }
12 
13 public function courses()
14 {
15 return $this->morphedByMany(Course::class, 'taggable');
16 }
17}

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.

1$tag = Tag::find(1);
2$posts = $tag->posts()->get()->map(fn($post) => [
3 'id' => $post->id,
4 'title' => $post->post_title
5]);
6 
7$videos = $tag->videos()->get()->map(fn($video) => [
8 'id' => $video->id,
9 'title' => $video->video_title
10]);
11 
12$courses = $tag->courses()->get()->map(fn($course) => [
13 'id' => $course->id,
14 'title' => $course->course_title
15]);
16 
17$results = collect()->merge($courses)->merge($posts)->merge($videos);

This code will return this structure, if there is a Post/Video for the tag but no Course:

1Illuminate\Support\Collection {#2198
2 all: [
3 [
4 "id" => 1,
5 "title" => "Post about Eloquent",
6 ],
7 [
8 "id" => 1,
9 "title" => "Video comparing Vue and Livewire",
10 ],
11 ],
12}

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Recent Premium Tutorials