Jamie Jamie - 22 days ago 9
PHP Question

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?

Answer

You should pass a key / value pair to the contains method, which will determine if the given pair exists in the collection.

You should use contains() method in this way:

foreach ($this->options as $option) {
  // Pass key inside contains method
  if($options->contains('id', $option->id)) {
      dd('test');
  }
}

Hope this helps

Comments