<?php $post = Post::get(); // get the "Post" model instance if ($post->first()) { } if (!$post->isEmpty()) { } if ($post->count()) { } if (count($post)) { } if ($post->isNotEmpty()) { }
Method 1: Check Collection Not Empty with first() Function
The 1st method is to use the "first()" function and if the collection exists, the first record from the collection will be retrieved.
<?php if ($post->first()) { // dd($post); }
Method 2: Check Collection Not Empty with isEmpty() Function
The 2nd method is to use the "isEmpty()" function and although it checks if the collection is empty you can make use of the "!" not operator. By doing so you will get the reverse value.
<?php if (!$post->isEmpty()) { // dd($post); }
Method 3: Check Collection Not Empty with count() Function
The 3rd method is to use the "count()" function and this can be called from the collection instance itself since by default the base class implements the "countable" interface.
<?php if ($post->count()) { // dd($post); }
Method 4: Check Collection Not Empty with count() Function
The 4th method is to use the normal "count()" function and this will internally count the total number of collections.
<?php if (count($post)) { // dd($post); }
Method 5: Check Collection Not Empty with isNotEmpty() Function
The last method is to use the "isNotEmpty()" function and this check if the collection is not empty.
<?php if ($post->isNotEmpty()) { // dd($post); }
Full Code Example
Those are the ways to check whether a collection in Laravel is empty or not and once you have done that you can perform your looping and any other code logic.
<?php if ($post->isNotEmpty()) { Post::each(fn ($post) => /* do something with $post here */) }
Leave a reply