SergkeiM
SergkeiM

Reputation: 4168

Relation is not removed when calling unsetRelation()

unsetRelation('relation') is not removed when calling pluck('relation')

$data = Model::with([
        'child', 'child.one', 'child.two'
])->get()

Removes 'child.one' and 'child.two' but keeps child

$data->transform(function ($item, $key) {
    if($key == 1){ //remove the second item
              $item->unsetRelation('child'); //same behavior if we call $item->unsetRelations();  
        }
        return $item;
});

$output = $data->pluck('child');

After calling pluck if we had 2 items under $data->child, the first contains all 3 relations ( child, child.one, child.two), the second item contains only child. I guess if we call unsetRelation should not return it after pluck method?

If we call dd($data) after transform relation is not there.

Update

$items = Model::with([
    'child',
    'child.one',
    'child.two'
])->get();

$items->transform(function($item, $key) use ($request){

    if($this->filter($item->child, $request)){ //check if need to exclude

        $item->child->param_1 = $item->id; //as example there is more logic

    }else{

        $item->unsetRelation('child');

    }

    return $item;

});

return $items->pluck('child');

Upvotes: 0

Views: 1848

Answers (1)

N69S
N69S

Reputation: 17205

When you do a pluck on an attribute that is a relation, it will be loaded if the relation is not already present.

For your example, you can $data = Model::get() then $data->pluck('child'); you will get the child of each one and not an empty collection.

To remove a relation specifically for a collection pluck, set the relation as empty

$data->transform(function ($item, $key) {
    if($key == 1){ //remove the second item
          $item->setRelation('child', collect([]);
    }
    return $item;
});

This will make the relation marked as loaded and still returning and empty result.

Upvotes: 1

Related Questions