Emmanuel-Ab
Emmanuel-Ab

Reputation: 331

How to search for a value in array of objects and get it in Laravel?

How to search an array of objects and get a specific value if exists, and if not, take something else in Laravel 5.8?

Collection{
    #items: array:3[
       0 = Object{
         attributes[
         "id" => 1
         "name" => 'google'
         "url" => 'https://google.com/'
         ]
       }
       1 = Object
       2 = Object
    ]
}

So out of this how to check if in this array there is an attribute url that has google.com in it? If something like this does not exists than get something else?

Is it possible to do this without looping?

Upvotes: 1

Views: 4743

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

Assuming the collection variable is $sites, you should be able to use the ->contains() closure to check if any of the $sites contains the google url:

$hasGoogle = $sites->contains(function ($site, $key) {
    return $site->url == 'https://google.com';
});

if ($hasGoogle) {
    // do something
} else {
    // do something else
}

A boolean is returned from the ->contains() method.

Upvotes: 7

Related Questions