@amitsolanki24_ It's because you applied the take method within each is not modifying the original collection items because each is used for iteration without modifying the items, and the changes to the countries relationship need to be explicitly assigned back using setRelation.
Try this:
$items->each(function ($item) {
// Limit countries to 5
$item->setRelation('countries', $item->countries->take(5));
});
@amitsolanki24_ Honestly, there are many ways to solve your issue.
However, I don't prefer your approach.
Why?
You are bypassing Eloquent’s relationship management methods that ca lead to unexpected behavior or issues.
Also, you are manually unsetting and reassigning properties might lead to inconsistencies or bugs if there are other parts of the code relying on the original relationship.
Ofcourse, it's your preference which approach you will go, but surely I won't prefer to use manual unset().
@amitsolanki24_ Your thinking is wrong. Objects are passed to views by reference, so they're not going to consume any more memory or slow down the page load.
And even if they weren't, i.e. if the data was deep-copied, the amount of memory would be meaningless in the big picture.