How to filter by NULL in Eloquent Collections Laravel

Categorized as Laravel Tagged , ,

Eloquent collections are one of the most powerful tools in the Laravel toolbox. They give you a fluent, convenient wrapper for complex SQL queries. You can chain together different conditions to create complex queries and then call methods on the resulting collection to fetch your data.

And here comes the trap. For example, you filter by NULL in Eloquent, and then, if you’re filtering the collection further – filter by empty string, there’s no “null” in that field anymore!

See the code below:

// ✅
$messages = Message::where('read_at is null')->get();

// ❌ - will return 0 messages
$messages = Message::all();
$unread_messages = $messages->where('read_at is null')->count();

// ✅
$unread_messages = $messages->where('read_at', '')->count();

Leave a reply

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