Skip to content

Instantly share code, notes, and snippets.

@chrishow
Last active December 21, 2023 12:47
Show Gist options
  • Save chrishow/b15cc8950504db215db601eee1ffb64c to your computer and use it in GitHub Desktop.
Save chrishow/b15cc8950504db215db601eee1ffb64c to your computer and use it in GitHub Desktop.
Case insensitive 'where' filter for Laravel Collections
<?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