Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SpuriouslyAwake's avatar

Perform a search on a collection

I've been trying to find a way to search through a Collection to find a specific value. I've looked at search packages like Scout and Searchy but they all seem to work directly on the Model, bypassing the Eloquent relations. In my case I want to first filter the results based on the relations using whereHas and only then perform a search on the returned collection.

Something like this would be ideal:

$collection = Activity::whereNull('finished_at')->whereHas('assessment')->get();
$filteredResults = $collection->search($query)->get();

Has anyone found a way to achieve that functionality? Is there a cleaner way that converting to arrays and performing nested search functions using in_array etc?

Thanks

0 likes
4 replies
SaeedPrez's avatar

Explain more what you want to search for, is it the activity results or the assignments and why can't you add that search in the query?

SpuriouslyAwake's avatar

Ideally, the search functionality would not be tied to this particular example.

In this case I would like to find Activities that have assignments and then perform a fuzzy search to that a user can filter down the results based on some query.

I.e. an Activity has a relationship to GroupParticipant, who is related to User who has a name. So by performing a query 'Tom' on the $collection I would like to return only the Activities who have that string present anywhere within the Activity model (which includes the relationships).

I could add that search to the query but at the point of getting the $collection i don't know which fields the query will pertain to. The query string should be able to be found in any field in the model.

I hope that clarifies it a little bit

SaeedPrez's avatar

@SpuriouslyAwake like suggested by previous poster, you will need to use collection methods like each, filter, reject, etc to check each activity and also assignments depending on your needs.

You will need to iterate the activities to search the relationships..

Please or to participate in this conversation.