Last active
December 21, 2023 12:47
-
-
Save chrishow/b15cc8950504db215db601eee1ffb64c to your computer and use it in GitHub Desktop.
Case insensitive 'where' filter for Laravel Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* $collection = collect([ | |
* [ | |
* 'name' => 'Chris' | |
* ], | |
* [ | |
* 'name' => 'Monica' | |
* ] | |
* ]); | |
* | |
* $collection->where('name', 'chris'); | |
* // result: null | |
* | |
* If you want a case insensitive 'where' filter, | |
* add this to your AppServiceProvider's boot method | |
* | |
* usage: | |
* $collection->whereCaseInsensitive('name', 'chris'); | |
* // result: ['name' => 'Chris'] | |
* | |
*/ | |
\Illuminate\Support\Collection::macro('whereCaseInsensitive', function (string $field, string $search) { | |
return $this->filter(function ($item) use ($field, $search) { | |
return strtolower($item[$field]) == strtolower($search); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment