Laravel集合搜索不区分大小写

11

我正在搜索一个集合,希望这个搜索不区分大小写,或者至少将集合的值更改为小写。我该如何做?

$value = strtolower($value);
$collection = $collection->where($attribute, $value);

$value是小写的,而集合中的内容不是,所以没有匹配项。

4个回答

16

你可以使用 filter() 方法和一个回调函数来实现你想要的功能:

$collection = $collection->filter(function ($item) use ($attribute, $value) {
    return strtolower($item[$attribute]) == strtolower($value);
});

过滤器(Filter)和Where之间有什么不同? - Stefano Maglione
@Stefano Maglione,“where”在内部使用“filter”,而“filter”又使用“foreach”。我知道filter能够更好地处理集合,并且添加更多的约束等功能。 - Oluwatobi Samuel Omisakin

0
你可以对集合进行映射,并将每个项目的属性转换成小写:
$value = strtolower($value);
$collection = $collection
    ->map(function ($item) use ($attribute) {
        $item->{$attribute} = strtolower($item->{$attribute});

        return $item;
    })
    ->where($attribute, $value);

那会改变集合的内容。我认为OP只想根据条件过滤项目。 - Martin Bean
@MartinBean,没错,你的解决方案更好。 - thefallen
@StefanoMaglione,您能否在您的问题中添加$collection、$value和$attribute是什么? - thefallen

0
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    { 
        Collection::macro('locate', function (string $attribute, string $value) {
            return $this->filter(function ($item) use ($attribute, $value) {
                return strtolower($item[$attribute]) == strtolower($value);
            });
        });
    }
}

使用方法如下:

$collect->locate("sku", "KFALTJK2321")->first()

0

我创建了一个集合宏,用于执行不区分大小写的搜索。

下面的版本将获取与不区分大小写项匹配的集合中的第一项。

将此添加到您的服务提供者:

    Collection::macro('insensitiveFirstWhere', function ($key, $value = null) {
        if (func_num_args() === 1) {
            $value = true;
        }
        else if (is_string($value)) {
            $value = mb_strtolower($value);
        }

        return $this->first(function ($item) use ($key, $value) {
            $itemValue = $item->{$key};
            if (is_string($itemValue)) {
                $itemValue = mb_strtolower($itemValue);
            }
            return $itemValue == $value;
        });
    });

使用它,只需调用:

$collection = collect(['name' => 'John'], ['name' => 'Bobby']);
// will return John, as 'John' == 'john'
$collection->insensitiveFirstWhere('name', 'john');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接