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

BrahimBJZ's avatar

Filter data from an Laravel Collection with “LIKE” and not WHERE

I have the following method in laravel that basically gets all the parameters that are passed by URL, and inside the loop it checks that they are valid and if so filter the data from the collection with the where() method that comes with the Laravel collections.

protected function filterData(Collection $collection, $filters)
{
    foreach (request()->query() as $query => $value) { // Loop through parameters
        if (isset($query, $value) && in_array($query, $filters)) { // Validation
            $collection = $collection->where($query, $value); // Filter with where()

            // $collection = $collection->like($query, $value); // Desired method
        }
    }

    return $collection;
}

The problem I have is that I would like the filter to act as a "LIKE" instead of "WHERE". In other words, if the filter is ?name=Jhon, then I would also select the value "John Last Names". Sorry for my bad english

0 likes
3 replies
MichalOravec's avatar

Use filter for that

$collection = collect($data)->filter(function ($item) use ($search) {
    return false !== stripos($item, $search);
});
9 likes
jlrdw's avatar

Why don't you just use a query instead of collections.

1 like
arifsetyo21's avatar

@jlrdw in my case, i only use google sheet as database, so can only use collection instead of regular query language

Please or to participate in this conversation.