i want to filter a collection by name like "%something%" in laravel but where like doesn't work in collection how can i resolve this issue? i wrote this method and doesn't work for name filter
protected function filterData(Collection $collection, $transformer)
{
foreach (request()->query() as $query => $value) {
$attribute = $transformer::originalAttribute($query);
if (isset($attribute, $value)) {
if ($attribute == 'name') {
$collection = $collection->where($attribute,'LIKE' ,"%$value%"); // problem is here
}
$collection = $collection->where($attribute, $value);
}
}
return $collection;
}
You can filter your collection like this:
$collection = $collection->filter(function ($item) use ($attribute) {
return strpos($item->name, $attribute) !== false;
});
If you get an error saying Trying to get property 'name' of non-object
, just change $item->name
to $item['name']
.
Change to this
$collection = $collection->where($attribute,'LIKE',"%".$value."%"); // problem is here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.