DEV Community

Morcos Gad
Morcos Gad

Posted on

Laravel contains() & containsStrict() Method

Let's get started quickly, I found two great Method contains() and containsStrict() so you can use them in your next projects

  • Check if Laravel Collection contains value Let's review an example with one parameter (checking only value)
$users = collect(['name' => 'John Doe', 
                  'email' => 'johndoe@example.com']);

$users->contains('John Doe'); // true
$users->contains('John Admin'); // false
Enter fullscreen mode Exit fullscreen mode
  • Check if Laravel Collection contains key/value pair Let's review an example with two parameters
$collection = collect([
             ['id' => '200', 'amount' => '500'],
         ['name' => '201', 'country' => '200'],
              ]);

$collection->contains('amount', '500'); //true
$collection->contains('id','500'); //false
Enter fullscreen mode Exit fullscreen mode
  • Check if Laravel Collection contains value using callback function Lastly, you can also pass callback function with your own matching expression to check whether laravel collection or eloquent collection contains given value or not Let's try an example with eloquent collection this time
$products = Product::all();
/*
Illuminate\Database\Eloquent\Collection {#4618
     all: [
                App\Product {#123
                    id: 1,
                    name: "Macbook",
                    product_count: 2
                },
                App\Product {#123
                    id: 1,
                    name: "iPhone",
                    product_count: 20
                },
            ],
        }
*/
$products->contains(function($product, $key) {
            return $product->product_count < 5; 
      }); //True

$products->contains(function($product, $key) {
            return $product->product_count < 1;
      }); //False
Enter fullscreen mode Exit fullscreen mode
  • Laravel containsStrict() Method Laravel Collection's containsStrict() method function same as contains() method except it checks for value using strict comparison i.e matches value type as well If you don't know about strict comparison, in PHP === and !== are strict comparison operators and it compares both value and type. Example: 20 and "20" are not equal in strict comparison but are same in regular comparison
$collection = collect(["10","11","12"]);

$collection->containsStrict("10"); //true

$collection->containsStrict(10); //false
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code
Source :- https://www.parthpatel.net/laravel-contains-method-example/

Top comments (0)