In Laravel, collections are a common way to store and work with data. Sometimes, we need to check collection is empty or not in Laravel before performing operations to avoid errors or unexpected results. The Collection class provides many methods similar to array functions, making it easy to manipulate and access data.
There are several ways to determine if a collection has no items, such as using isEmpty(), count(), or first(). Let’s explore these methods 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.
While working with collections in Laravel, you might often need to share or store data in a standard format. For handling such cases, you can convert collection into JSON in Laravel, which makes it easy to use in APIs or front-end applications.