In this episode, we're focusing on how to attach and detach multiple related models in Laravel at once. Instead of adding or removing one relation at a time, you'll see how simple it is to work with arrays or collections to handle batch operations.
We start by duplicating our attach route, calling it "attach many," and see how you can pass an array of IDs to link all your topics to a course in one go. For example, if you have topic IDs 1 through 4, you simply pass [1, 2, 3, 4]
and attach them all at once. It's just as easy on the detach side—you can detach multiple topics by giving their IDs in an array.
But what if you want to work directly with Eloquent collections, not arrays? We check out how Laravel handles it effortlessly: you can pass a collection of topic models directly into the attach
method, and Laravel figures it out behind the scenes, attaching all those relations. The same trick works with detaching—just pass a collection to detach
.
While this is super handy when your UI or logic gathers multiple IDs or models, be aware that if you want to update the full list of related things, just detaching all and reattaching isn't optimal. Toward the end, we hint that there's an even better way—syncing relationships—which we'll explore later in this section. For now, you should have a solid grasp on efficiently attaching and detaching many related records at once using arrays or collections in Laravel!