Current Location: Home> Latest Articles> How to Check if Database Query Results Are Empty in Laravel

How to Check if Database Query Results Are Empty in Laravel

gitbox 2025-07-14

How to Check if Database Query Results Are Empty in Laravel

In Laravel, querying the database is a common task, often performed using Eloquent or Query Builder. After executing a query, it's important to check if the returned results are empty to avoid potential errors in subsequent code.

Ways to Query the Database

Laravel provides two common methods for querying databases: Eloquent and Query Builder. Eloquent offers an object-oriented approach to database operations, while Query Builder uses a chainable query syntax.

Eloquent

Eloquent is Laravel's built-in ORM, which allows you to define models for interacting with the database. Here is an example of querying with Eloquent:


// Define model
class User extends Illuminate\Database\Eloquent\Model {
    protected $table = 'users';
}

// Query database
$user = User::find(1);

In the code above, we define a model called User and set its associated database table to users. We then query the users table for the record with a primary key of 1 using User::find(1).

Query Builder

Query Builder is another method in Laravel for querying the database. It supports chainable methods, resulting in clean and concise code. Here's an example of querying using Query Builder:


$users = DB::table('users')->get();

This code will return all records from the users table.

Checking if Query Results Are Empty

After executing a query, it's necessary to check whether the results are empty. Here are two common ways to do that:

Method 1: Check if Query Result Count is 0

You can check if the query result is empty by examining the count of results. Here's how you can do it:


$users = DB::table('users')
            ->where('name', '=', 'John')
            ->get();

if ($users->count() > 0) {
    // Results are not empty
} else {
    // Results are empty
}

By calling count(), you can get the number of records returned by the query. If the count is greater than 0, the results are not empty.

Method 2: Use the empty() Function

The PHP empty() function can also be used to check if the query result is empty. Here's how you can use empty():


$users = DB::table('users')
            ->where('name', '=', 'John')
            ->get();

if (!empty($users)) {
    // Results are not empty
} else {
    // Results are empty
}

By using !empty($users), if the query result is not empty, it will return true; otherwise, it will return false.

Conclusion

In Laravel, querying the database is a common task that can be easily done using Eloquent or Query Builder. After executing the query, checking if the results are empty is crucial. The two common methods for checking are by result count or using the empty() function. Mastering these techniques will help developers avoid issues caused by empty data in their applications.