You can find the collection search method inside Illuminate\Support\Collection class. If you are not familiar with Laravel Collections, then check out my Laravel Collections guide.
Laravel Search
Laravel search() is a built-in collections method that is used to search the collection for a given value. If the value is present in the collection, the key of the value is returned. If the value does not match any item, false is returned. The search is done using the “loose” comparison, meaning the string with the integer value will be considered equal to the integer of the same value.
To use a “strict” comparison, we must pass true as the second argument to the method.
public function search($value, $strict = false) { if (! $this->useAsCallable($value)) { return array_search($value, $this->items, $strict); } foreach ($this->items as $key => $item) { if (call_user_func($value, $item, $key)) { return $key; } } return false; }
Under the hood, the collection search() method calls array_search() method.
See the following example.
Write the following code inside the routes >> web.php file.
<?php // web.php Route::get('/', function () { $collection = collect([21, 19, 46, 29]); echo $collection->search(19)."\n"; });
Now, run the laravel project and you will see the following output 1. That means, 19 is there in the array, and its key is 1 which is returned.
Now, let’s search with a strict comparison. See the following code.
<?php // app.php Route::get('/', function () { $collection = collect([21, 19, 46, 29]); echo $collection->search('19', true); });
The output will be false because we are searching 19 as a string and not an integer and we are checking in strict mode because we have passed the second parameter as a true.
Alternatively, you may pass in your callback to search for the first item that passes your truth test. It will return the first item’s index as an output. See the following code.
<?php // app.php Route::get('/', function () { $collection = collect([19, 21, 46, 29]); echo $collection->search(function($item, $key) { return $item > 19; }); });
In the above code, we are checking each collection item to be > 19. Now, 21 is the first element which is > 21, and its index is 1. So the output will be 1.
That’s it for this tutorial.