Laravel 9: how to use 'when' method within collection pipeline after eager loading
I'm confused about I'm working with an scenario with Laravel 9 when trying to use the `when` method on a collection after eager loading relations... The goal is to conditionally modify the collection based on the presence of a specific attribute. However, the `when` method doesn't seem to behave as expected in this context. My model `Post` has a `comments` relationship, and I'm trying to filter the comments based on the `approved` status. Hereβs the code I've written: ```php $posts = Post::with('comments')->get(); $filteredPosts = $posts->map(function ($post) { return $post->setAttribute('filtered_comments', $post->comments->when( $someCondition, function ($comments) { return $comments->where('approved', true); } )); }); ``` However, I'm getting the following behavior: ``` Call to a member function when() on a collection ``` I've tried using `filter` instead of `when`, but that doesn't achieve the same result and feels less elegant. The `$someCondition` variable is set correctly, and I know that the `comments` relationship is eager loaded. I also checked that `comments` is indeed a collection when this part of the code executes. Could someone guide to understand why the `when` method isnβt working in this scenario? Is there an alternative approach to conditionally modify the comments collection while maintaining clarity in the code? I'm developing on Ubuntu 22.04 with Php. Is this even possible?