Home / Snippets / How to Check Collection not Empty in Laravel 8
How to Check Collection not Empty in Laravel 8 cover

How to Check Collection not Empty in Laravel 8

1.4K

3 years ago

0 comments

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!
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this