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?
Laravel contains() Methodcontains() method checks whether Laravel Collections contains certain given value or not. If you pass one value to the contains() method, it will check whether collection has any value matching to the parameter.
If you use all() , get() methods then you'll get a collection object, it means a collection of User models when you use these methods on User model and remember all() and get() always returns a collection of models even if there is only one model in it, so check this examaple: $users = User::all(); // returns a ...
You should pass a key / value pair to the contains method, which will determine if the given pair exists in the collection. Use contains()
method in this way:
foreach ($this->options as $option) { // Pass key inside contains method if($option->contains('id', $option->id)) { dd('test'); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With