I need to use filters to generate a collection with Laravel. I have a Project
model which has many Investment
s. I make a query and retrieve a collection at the $projects
variable. Then, there is a collection inside each one of the $projects
collection called investments
. I need to retrieve only the projects which have investments such that:
$investments->status = 'paid' && $investments->user_id is contained in $users_list
I used two nested filters, one for the projects collection and another one for the investments collection. I use the inner investments collection to filter by status
and user_id
and assign the filtered collection to $filtered_investments
. Then I try to modify the unfiltered investments collection inside each project collection and replace it by $filtered_investments
, however that does not happen. The investments filter works well but $filtered_projects
contains its original investments collection instead the one I calculated.
Is there a way to do this? Thanks!
$projects = Project::has('investments')
->with('investments')
->get();
$users_list = [54];
$investment_status = 'paid';
$filtered_projects = $projects->filter(function($proj_value,$proj_key) use ($users_list,$investment_status){
// Calculate the filtered_investments collection checking the status and user_id fields
$filtered_investments = $proj_value->investments->filter(function($inv_value,$inv_key) use ($users_list,$investment_status){
$return = $inv_value->status == $investment_status && in_array($inv_value->user_id,$users_list);
return $return;
});
// Here I have a new filtered_investments collection which I want to assign to
// the current project investments field.
$proj_value->investments = $filtered_investments;
// This is only to return the current project if there is at least one
// element inside $filtered_investments
return $filtered_investments->count() > 0;
});