vincent15000's avatar

Strange behavior of the filter collection helper

Hello,

When I filter a collection of some model, I get a strange behavior.

The filtered collection seems to have eager loaded all relationships for each nested model. But I don't need to eager load anything. And before filtering, I don't have eager loaded any relationship.

Here is my filter code.

$courses->filter(function ($course) {
    return auth()->user()->can('view', $course);
});

How is it possible ?

Thanks for your help to understand this.

V

0 likes
4 replies
vincent15000's avatar

I think I have found the answer.

In my view policy, I retrieve some relationship to check the authorization.

What I would like now is to load this relationship only locally inside the policy.

Snapey's avatar

@vincent15000 and then a few lines later when you need to check the policy again, you load the relation again?

1 like
vincent15000's avatar

@Snapey I don't really load the relationship in the policy, I just access it. But effectively I generally load the relationships before using the policy, it's more performant.

Just accessing a relationship loads it definitely ?

Snapey's avatar
Snapey
Best Answer
Level 122

@vincent15000 how else?

if you do auth()->user()->related->someattribute then the user model will be hydrated with the data

if you do $related = Related::where('user_id', auth()->id)->first(). then the related model is assigned to the variable and will be destroyed when the function ends.

1 like

Please or to participate in this conversation.