How to Check If Laravel Collection is Empty?

How to Check If Laravel Collection is Empty?

Hello Artisans.

In this quick tutorial, I will show you how to check if the laravel collection is empty or not. This article goes into detail on how to check if the database collection is empty laravel. I will show you several examples to check collection is empty laravel. 

These examples are useable for laravel 6 and greater versions. 

So, let's get started one by one. 

Example 1: Using isEmpty()

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $products = Product::get();
  
        if ($products->isEmpty()) { 
            dd("Products eloquent collection is empty.");
        }else{
            dd("Products eloquent collection is not empty.");
        }
    }
}

 

Example 2: Using isNotEmpty()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $products = Product::get();

        if ($products->isNotEmpty()) {
            dd("Products eloquent collection is not empty.");
        }else{
            dd("Products eloquent collection is empty.");
        }
    }
}

 

Example 3: Using count()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $products = Product::get();

        if ($products->count()) {
            dd("Products eloquent collection is not empty.");
        }else{
            dd("Products eloquent collection is empty.");
        }
    }
}

 

Example 4: Using first()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $products = Product::get();

        if ($products->first()) {
            dd("Products eloquent collection is not empty.");
        }else{
            dd("Products eloquent collection is empty.");
        }
    }
}

Conclusion

In this quick guide, We have learned how to check if the laravel database collection is empty. I have provided several examples to check whether the laravel collection is empty or not. 

 

I hope, it will help you. 
Happy Coding :)

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×