In this episode, we're diving deep into how to manage tags for our articles
and courses
models—basically covering all the ways you can attach, detach, and sync many-to-many relationships in Laravel. We start off by exploring the attach
method: how to use it to add tags to an article (either by ID or by passing in the Tag model itself), and how to handle single or multiple tag attachments at once.
You'll see firsthand what happens if you keep attaching the same tag multiple times (spoiler: you'll get duplicates!) and learn how to avoid that problem. Then we flip things around and look at detach
, showing you how to remove tags individually or clear them all out in one go.
Next, we dig into sync
, which is super useful when you want to ensure the tags an article has exactly match a set of IDs—replacing any old ones. But what if you want to add tags without removing the existing ones? That's where syncWithoutDetaching
comes in, letting you add new tags while keeping the current ones intact.
Throughout the episode, you'll get a feel for how flexible and powerful Eloquent's many-to-many relationship methods are, and you’ll see all the changes reflected in the UI in real time. By the end, you'll have a solid grip on attaching, detaching, and syncing tags—the core ways you'll handle many-to-many relationships in real-world Laravel apps. There's a couple more advanced methods we could use, but we'll save those for another episode!