Eloquent select rows with empty string or null value

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company

Selecting Rows with Empty Strings or Null Values in Laravel Eloquent

In Laravel Eloquent, there might be instances where you need to filter your model's relations based on the value of a specific column. In this case, you may encounter scenarios where you want to retrieve rows with either empty strings or null values in that field. The following blog post will provide a comprehensive solution and best practices for handling these types of queries.

The Original Code

$user->albums()->where('col', NULL)
This code works fine when filtering based on null values. However, it fails when you try to extend it to include empty strings as well:
$user->albums()->where('col', NULL)->or_where('col', '')
The line above doesn't seem to work correctly, resulting in unexpected behavior. You might have also noticed that the official documentation does not document a method for dealing specifically with empty strings or null values. Luckily, there are other ways to achieve what you're looking for without relying on undocumented methods.

Solution 1: Using the OrWhere Method

You can use Laravel's where() and orWhere() methods to handle this case more explicitly:
$user->albums()->where('col', '=', null)
    ->orWhere('col', '=', '')
This code will return rows with null values in the column or those with empty strings. The "= null" operator ensures that only rows with null values are selected, while the "= ''" operator handles empty string values.

Solution 2: Using Query Builder's Where Clauses

An alternative approach is to use Laravel's whereRaw() method, which allows you to run raw SQL queries on your database:
$user->albums()->whereRaw('col is null')
    ->orWhereRaw('col = ""')
This code will return the same result as before, but it's essential to note that you should be cautious when using raw SQL since it may introduce potential security risks. In this case, make sure your database connection is configured properly and that you are only running trusted queries.

Conclusion

In conclusion, if you need to select rows with empty strings or null values in a specific column of your Laravel Eloquent model's relations, there are multiple ways to achieve this goal. Using the ORWhere method with explicit operators, as shown in Solution 1 and 2, is probably the most straightforward approach for handling complex filtering requirements. However, it's essential to be aware of potential security risks when using raw SQL queries. Always ensure you have a proper database connection configuration to avoid any vulnerabilities.