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!