Laravel Collection search() Method

Laravel search() is a built-in collections method 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, a false is returned. The search uses 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 the 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";
});

Run the laravel project, and you will see the following output 1. That means 19 is 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 the strict mode because we have passed the second parameter as 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.

<?php

// app.php

Route::get('/', function () {
   $collection = collect([19, 21, 46, 29]);
   echo $collection->search(function($item, $key) {
   return $item > 19;
 });
});

The above code checks 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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.