'Laravel collection contains

I'm using the Laravel contains method on a collection https://laravel.com/docs/5.3/collections#method-contains. But it does not work for me.

foreach ($this->options as $option) {
    if($options->contains($option->id)) {
        dd('test');
    }
}

dd($options); looks like this:

Collection {#390
  #items: array:1 [
    0 => array:3 [
      0 => array:7 [
        "id" => 10
        "slug" => "test"
        "name" => "test"
        "poll_id" => 4
        "created_at" => "2016-11-12 20:42:42"
        "updated_at" => "2016-11-12 20:42:42"
        "votes" => []
      ]
      1 => array:7 [
        "id" => 11
        "slug" => "test-1"
        "name" => "test"
        "poll_id" => 4
        "created_at" => "2016-11-12 20:42:42"
        "updated_at" => "2016-11-12 20:42:42"
        "votes" => []
      ]
      2 => array:7 [
        "id" => 12
        "slug" => "test-2"
        "name" => "test"
        "poll_id" => 4
        "created_at" => "2016-11-12 20:42:42"
        "updated_at" => "2016-11-12 20:42:42"
        "votes" => []
      ]
    ]
  ]
}

Result of dd($option->id); is 10.

What could be wrong? Or is there a better way?



Solution 1:[1]

Use the following, which tells Laravel you want to match the 'id':

$options->contains('id', $option->id);

Docs

Solution 2:[2]

foreach ($this->options as $option) {
    if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) {
        dd('test');
    }
}

Solution 3:[3]

The contains method determines whether the collection contains a given item. There are basically three ways in which it can be used :

  • simply checking the item
$collection = collect(['name' => 'Sarah', 'age' => 23]);

$collection->contains('Desk');

// false

$collection->contains('Sarah');

// true
  • checking the key/value pair :
$collection = collect([
    ['name' => 'Sarah', 'age' => 23],
    ['name' => 'Vicky', 'age' => 34],
]);

$collection->contains('name', 'Hank');

// false
  • checking via callback function :
$collection = collect([3, 5, 7, 9, 11]);

$collection->contains(function ($value, $key) {
    return $value < 2;
});

// false

Now, for your problem, we will use the second category, i.e :

foreach ($this->options as $option) {
   // here id is key and $option->id is value
  if($option->contains('id', $option->id)) {
      dd('test');
  }
}

Link to docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jan Willem
Solution 2 Don
Solution 3 Adesh Khanna