In this episode, we're diving into how to handle the inverse side of a polymorphic many-to-many relationship. Instead of just seeing which tags are attached to an article (like we've done already), we're flipping things around: for a given tag, we'll see which articles (or even courses) are linked to it.
We start by syncing some tags with articles as a demo. Then, we build out a simple route to view a tag and show all articles associated with it. There's no controller right now – just a quick closure and some basic routing with route model binding. We update the homepage so that tags are clickable, leading to a tag details page with all its related content.
As we set up the new view for tags, we talk through how the inverse relationship works in Laravel and implement it in code using morphedByMany
. This lets us pull out all articles and courses for a tag, and we show how to expand this for different content types.
We also add in support for showing pivot table data (like a version number) in the tag details page. The same trick lets you show extra info, like timestamps, or order results if you want. Finishing up, now you have a fully flexible system: you can click into a tag, see all connected resources, view their extra pivot information, and of course, jump right back to the article side as well.