Posts Learn Components Snippets Categories Tags About
/

How to Check Collection not Empty in Laravel 8

Learn how to check if a collection is not empty in Laravel 8 the easy way from the backend and blade views.

Created on Sep 07, 2021

27 views

Sometimes you might need to check for a collection whether it's empty or not before looping them in Laravel and there are several ways to do it. To check collection is not empty in Laravel, you can make use of one of the following functions. For this example, we'll be checking whether the "Post" model collection is empty or not.
<?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 */)
}
If you found this snippets to be helpful do make sure to share it with your friends, cheers!

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to Check Collection not Empty in Laravel 8

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More