Laravel 'A%' 的收集过滤器就像我们对 'A%' 的地方所做的一样

Laravel collection filter for 'A%' just like we do with where like 'A%'

我想过滤一堆以字符开头后跟通配符*

的名字

查询
我可以通过查询来实现,例如return $q->where('name', 'like', $name . '%');

因为我有 modal::class 缓存,我不想重复它而是使用 filter() 其他东西 可以帮助我获得预期的结果。

集合过滤器()

return $collection->filter(function ($q) use ($name) {
    return false !== stripos($q['name'], $name); // this returns all the names that contains $name character
});

我想要实现的是 filter() 以特定字符开头然后是 '%' 的名称 -- $name . '%' 例如'A%'

下面是我经历过的两个SOlink

您可以使用 Str::startsWith 助手。

use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

应用于您的代码,应该是

use Illuminate\Support\Str;

return $collection->filter(function ($q) use ($name) {
    return Str::startsWith($q['name'], $name);
});

对于 5.7 之前的 laravel 版本,请改用 starts_with 助手。

$result = starts_with('This is my name', 'This');

// true