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
$myCollection->filter(function ($item) {
return false !== stripos($item->comment, 'test');
});
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. :)
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.
});
Please or to participate in this conversation.