How to check a return value from database is empty or not in Laravel

When using Laravel Eloquent, we may have to check a return value from database query is empty or not. But the truth is method is_null() or method empty() can not work.

After debugging with dd() and var_dump(), I realize the below query always return an instance of Illuminate\Database\Eloquent\Collection even if there really is no matching data in the database. In PHP, we cannot tell an object is empty or not empty.

$result = Model::where(...)->get();   // $result is a Collection object
var_dump(empty($result));       // It will print true if no data match

In fact, Laravel Eloquent provides some ways to determine whether the result is empty.

var_dump($result->first());   // It will print null if no data match
var_dump($result->isEmpty());   // It will print true if no data match
var_dump($result->count());   // It will print 0 if no data match

Hope it helps you

RSS