Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection contains

Tags:

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?

like image 820
Jamie Avatar asked Nov 12 '16 19:11

Jamie


People also ask

Is collection Check in Laravel?

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.

What is collection and object in Laravel?

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 ...


1 Answers

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');   } } 
like image 78
Saumya Rastogi Avatar answered Oct 08 '22 05:10

Saumya Rastogi