Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How to Check Collection is Empty or Not in Laravel

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