This episode is for members only

Sign up to access "Mastering Polymorphic Relationships" right now.

Get started
Already a member? Sign in to continue
Playing
10. Many to Many: Defining the relationship

Transcript

00:00
So let's move on to something a little bit more complex but a lot more powerful and that is many-to-many polymorphic relationships. Now before we dive in and start writing any code, we're going to talk about why we might need these. So let's take a look at an example.
00:15
So we've already looked at having a bunch of articles with a bunch of comments, and we've already looked at having episodes with a bunch of comments as well. Let's change this up a little bit because I'm going to switch this to a course and articles. So what the goal here is, is to be able to apply a tag or something like that to both of these things.
00:36
So let's say that we had an article which was about Laravel, but it was also about Vue as well. So it combined Vue and Laravel. And then let's say we had a course which was about Laravel, but it was also about Blade or Alpine or something like that. What we basically want to do is apply a preset, and this is the key thing, a preset list of tags to each of these things.
01:01
So we have separately a tags table. Let's imagine that we have Laravel, Vue, Blade, whatever. So here, this is different to a one-to-many polymorphic relationship because we know that when we have a comments table, we have a specific ID and type that hooks up to what we're talking about here.
01:23
But a comment is one thing. A comment can exist on its own. It can't be reused between articles and courses, for example. So we can't have a comment posted on an article, which is the identical comment is posted on a course. Whereas with tags, the key here is reusability.
01:41
So when we talk about many-to-many polymorphic relationships, we're talking about the reusability of a predefined set of models in the database. So let's start with the most basic. What I've gone ahead and done is cleared out absolutely everything here so we can start fresh and focus on this. Let's start with the most basic thing, which requires no real polymorphic setup.
02:02
And that is to make out a model for the tag that we want to work with here. So let's create out a tag with a migration and a factory just in case. And let's head over to the create tags table. So a tag just exists on its own. So there's nothing to do with polymorphic relationships here. So we're going to have a string here with a title.
02:20
You'd probably have a slug or that kind of stuff, but we'll just keep things simple here with the title for now. And we'll go ahead and migrate this just before we do migrate. Actually, let's make this unique. Let's run that migration. OK, so let's just focus on our tags for now. So let's go over to our tags table, say Laravel,
02:37
create that out and we'll do the same thing for a couple of others as well. Let's pull this title out. What do we want? Let's say view. And let's say inertia. OK, great. So we've got three tags in here which we want to be applied to any amount of articles.
02:54
We want any of these tags to be applied to articles, courses, whatever models we're working with. So now let's go ahead and create out these other two things which we deleted earlier. So let's say article. And let's do the same thing for a course as well. OK, so let's say create articles table again.
03:17
We're going to keep this super simple and polymorphism does not come into this at the moment. Let's do the same thing for the create courses table. So string and title. And let's go ahead and run our migration. So, so far, nothing to do with polymorphic relationships.
03:39
Let's create out a couple of articles to demonstrate this. And the reason I'm doing this from scratch is just so it's easier for us to see what the whole process looks like here. So we've got article one and we've got article two. We'll keep it at that and we'll do the same thing for courses.
03:56
So we'll say course one. And we'll duplicate this down and we'll say course two. OK, save that out. And great. So now we have the opportunity to apply any of these tags that we've created. So we could apply Laravel and Vue to course one and we could apply Laravel and Inertia to course two.
04:20
And we could apply just Laravel to article one or just Vue to article two. Whatever we wanted to do. Hopefully you get the idea. So how do we hook this up with a many to many polymorphic relationship? Well, if you've worked with Laravel for any length of time, you'll know that the concept of databases for any length of time.
04:38
You'll know the concept of a pivot table where we can match things up. Now, a polymorphic many to many relationship in Laravel is basically just a polymorphic relationship that uses a pivot table. So now what we need to do is create out a pivot table for this. So we're going to say make migration. There might be an automated way to do this.
04:55
I'm not sure. We're going to go ahead and create a. Now we need to think of the name. So remember earlier when we had comments, we had commentable. We are working with tags, so we're going to call this tagable. So, again, it's entirely up to you how you name these.
05:10
I'm going to keep the convention and this should actually be tagables. If you don't keep the convention, you'll just need to pass them as the argument names. We need to find the relationship. So let's create tagables table. And once that's done, let's head over to the migration here.
05:26
Now, what do we want? Well, we don't necessarily need timestamps. We don't necessarily need an ID. I'm going to keep them in there anyway. Let's go ahead and find these out. So table. I'm going to say morphs once again. I'm going to say tagable ID or tagable. Sorry.
05:41
That will generate tagable ID and it will generate tagable type. Now, the other thing that we need to include in here, of course, is going to be the tag ID itself, because we need a tag ID to know which tag we are then hooking up to in here to either the article with an ID of one, the course and ID of one, course ID of two, whatever.
06:03
So let's go ahead and add in a foreign ID in here to the tag table. We don't need to define the table name in here. And we could say constrained if we want to make sure that that actually exists. And you could add any other constraints here, whatever.
06:19
OK, let's try this out. So let's go ahead and say PHP artisan migrate and we should be done. Now, before we look at the actual relationship within Varavel, we're going to go over and we're actually going to create some of these manually in the database. And then, of course, I'll show you in the next episode how to create these, modify these, whatever you need to do.
06:40
So this is where it gets a little bit more tricky to tag ID one. The tagable type is going to be an article. The tag ID is going to be one. So let's say created at now and updated at now. And OK, so we've got tag one on article one, tag two on article one, tag one on article two.
07:03
We'll have a tag three on article course one. We'll have tag three on course two. And let's just leave it at that. We'll leave a tag off of the other course. So that's basically how your table is going to end up looking once you start assigning tags.
07:24
You could do this within an admin panel or, you know, with custom functionality, whatever you want to do. OK, let's take a look at defining the relationship now. So this isn't too much more tricky. In fact, it's probably a little bit easier because we don't really need to define anything on the tag model itself like we did before, because we're really just associating these within that pivot table.
07:44
So the first thing I actually want to do is come over to the app service provider and I just want to make sure that these are hooked up properly. We've got article. What have we got now? We've got a course instead. So let's hook that up to our course model. And let's just make sure that all of these are pulled in and that looks good.
08:03
OK, so now over in whichever one we are wanting to define out a list of tags for. So an article has tags. We are going to go ahead and create out the tags relationship. Now, instead of the standard relationship that you'd find in Laravel, where you'd have this belongs to many, which is how you do if you had a pivot table as a standard non polymorphic relationship, in which case this wouldn't work.
08:27
We now have morph to many. So let's go ahead and say morph to many. Of course, what we are returning is a bunch of tags. So we're going to provide tag in there. And you guessed it. We're going to say taggables. Now, what taggables will do here is it will pick up the fact that we've called the table taggables. And of course, it will use the column names taggle type, taggle ID to work out what things are at or where things are at.
08:49
Let's try this out. So we'll define the same relationship, actually, for our course. So let's go to course.php and pull that in as well. Let's go over to our web routes and just, you know, have a play around with this. So let's say article. And in fact, let's grab. Yeah, let's go and return a view here.
09:11
Let's grab all articles. We can list through them and then it will sort of build into a real world example. So let's say article and latest and get. Let's go over to our home view and let's build this out. So for each. And that is going to be articles. As article. We will output the.
09:36
Article title and then down here just underneath. Let's output a bunch of tags. Let's just do this within within a div here. So we'll say for each. Article tags as tag. And I'm going to show you an easier way to output these in a list.
09:59
And, you know, if we want to link through to them and we're going to look at the inverse of the relationship as well. So we'll build this example up. Don't worry if at this point you're thinking, how could I do this? My own projects will cover pretty much everything. So let's say tag title. OK, we might need to tweak this, but let's go ahead and give this a refresh.
10:16
And yes, so article. There we go. And yeah, let's have a look here. So tagables tagables ID not found in field list. OK, so let's have a look at how we've defined this. Yes. So this should be the singular version of that. And that will help us look up the pluralized versions.
10:36
And there we go. So we've got article one, which has a tag of Laravel and Vue and article two, which just has a tag of Laravel. Now, of course, we've got some n plus one stuff that we could do here to egoload, but that's pretty much it. And now we can just really swap around tags between different things. If these were courses, we would see exactly the same thing. We've already determined that, you know, this was going to work for both of the different models.
11:04
But there we go. That is how you would define our tagging system within Laravel using polymorphic relationships. OK, so we've looked at the basics here. We're going to cover, like I said, pretty much everything about this. Let's go to the next episode and just look at how we sync or associate these polymorphic relationships, these tags with these articles. Just in case you're building a manual admin system and you need to know how to hook these up.

Episode summary

In this episode, we dive into the more advanced and super useful concept of many-to-many polymorphic relationships in Laravel. Before jumping into code, we talk about when you might want to use something like this. The classic example? A tagging system! For instance, you may want to be able to apply tags like "Laravel", "Vue", or "Inertia" to both articles and courses, with a predefined set of tags that can be reused everywhere.

We start by setting up the basics: creating a tags table and some sample tags, then simple articles and courses tables. The key difference from previous relationship types (like one-to-many) is that tags are reusable and not unique per parent item. So, a single tag like "Laravel" can be applied to any number of articles and courses — that’s where the many-to-many stuff comes in.

Next, we set up the pivot table taggables to link tags with any taggable model (articles, courses, etc.) via polymorphism. With some quick migrations and inserts, we show how the pivot table connects tags and other models by storing their type and ID.

From there, we define the actual relationship in the models using Laravel's morphToMany, making it simple to retrieve all tags for an article or course. We wire up some basic views to demonstrate listing articles with their respective tags, and deal with some small naming hiccups along the way.

By the end of this episode, you’ll see how to set up a flexible, reusable tagging system that works across multiple models. Stay tuned — next up, we'll look at how to actually sync or associate these tags in your own admin panel or app!

Episode discussion

No comments, yet. Be the first!