How to Check Collection is Empty or Not in Laravel 8?

In this tutorial, I will give you a simple example of How to check Collection is Empty or Not in Laravel.
so you can easily use it with your laravel 5, laravel 6, laravel 7, and laravel 8 application. so let’s see bellow example below that will help you a lot.

In Controller

At first, we write condition in the controller to Check Collection is Empty or Not in Laravel.

We have a products table in the database, let suppose if in the products table we have some data.

How to Check Collection is Empty or Not in Laravel
  
    public function ListProduct(){
      $productList = Product::get();
      if($productList->count() == 0) {
        return  '<h2>No Product Found !</h2>';
      }
      else{
        return  '<h2>Product Found !</h2>';
      }
      return view('product.list',compact('productList'));
    }

Output (If Table has Data)

We have a Product Model, and we write conditions, We count all the product data, and the products table has some data, then the condition works like this.

How to Check Collection is Empty or Not in Laravel

Output (If Table has No Data)

Let’s delete or truncate the products table data, and see the output.

How to Check Collection is Empty or Not in Laravel

If the products table has no data, then the condition works like this.

How to Check Collection is Empty or Not in Laravel

In Blade File

Let’s write the code in the Blade file, to check collection is empty or not or if the model has data or not.

    @if ($productList->count() > 0 )
       @foreach($productList as $pkglist)
        <h2>{{ $pkglist->name }}</h2>
        <p>{{ $pkglist->description }}</p>
       @endforeach
    @else
        <h2>No Product Found !</h2>
    @endif

In this tutorial, we learned, How to Check Collection is Empty or Not in Laravel, in Controller, and in the Blade file.

I hope this article will help you with your Laravel application Project.

Also Read : Show a message if data is null in laravel

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top