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

GodziLaravel's avatar

Is it possible to use `like` with "%" in a collection ?

Hello ,

I created a collection , and now when I do :

$myCollection= $myCollection->where('comment','test');

It returns results,

But if I do:

$myCollection= $myCollection->where('comment','like','%test%');

It's not working, which is normal because it's not an SQL request,

My question: is it possible in Laravel to use something similar to % when I filter a collection ?

Thanks

1 like
3 replies
MichalOravec's avatar
Level 75
$myCollection->filter(function ($item) {
    return false !== stripos($item->comment, 'test');
});
1 like
shawnyv's avatar

One approach would be to use a filter...

$myCollection = $myCollection->filter(function($item){
            return str_contains($item->comment, 'test');
        });

Probably not the most efficient thing in the world, but it does solve the problem. :)

1 like
neeonline's avatar

You can use the collection filter for that. The filter callback must return a boolean value.

To achieve the SQL like behavior you can use the PHP strpos native function which will return false with the searched value cannot be found:

$collection = collect([
  ['comment' => 'first comment'],
  ['comment' => 'test comment'],
  ['comment' => 'another comment'],
  ['comment' => 'forthy test comment'],
  ['comment' => 'comment test'],
  ['comment' => 'last comment'],
]);

$collection->filter(function ($item) {
  return strpos($item['comment'], 'test') !== false; // If strpos returns anything other than false, means 'test' exists somewhere in the string.
});
1 like

Please or to participate in this conversation.