Check whether collection is empty or not in Larave

The common data storage method in Laravel is collection. The Collection class allows you to chain its methods to perform fluent mapping and reduce the underlying array. It provides most methods like array methods.

There are many methods to check whether the collection is empty or not with examples. Let’s know more about them one by one with examples.

Using isEmpty() Method

The isEmpty() method checks whether specifically, the collection is empty or not and returns boolean as output.

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function users(){
        $users = User::get();
        if($users->isEmpty()){
            dd('User table has no data.');
        }else{
            dd('User data.', $users);
        }
    }
}

Using count() Method

The count() method returns the data count in a collection so we can perform the condition that if the count is greater than 0 then the collection object is not empty. Let’s take an example of the count method to check collection is empty or not:

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function users(){
        $users = User::get();
        if($users->count() > 0){
            dd('User table has no data.');
        }else{
            dd('User data.', $users);
        }
    }
}

Using first() Method

The first method returns the first data from the collection so here we apply the logic that if the collection has one or the first data then it’s not empty otherwise it’s empty.

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function users(){
        $users = User::get();
        if($users->first()){
            dd('User data.', $users);
        }else{
            dd('User table has no data.');
        }
    }
}

Using isNotEmpty() Method

The isNotEmpty() method is a reverse method of isEmpty(). As the name suggests the isNotEmpty() method checks collection has data. so we can apply further logic to it.

<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function users(){
        $users = User::get();
        if($users->isNotEmpty()){
            dd('User data.', $users);
        }else{
            dd('User table has no data.');
        }
    }
}

Conclusion

In this article, we have taken a few examples to check Laravel collection is empty or not. Here, we have seen 4 methods to check collection but the idle method for this concept is the isEmpty() method.