How to check Eloquent get() and first() query result - BOOKC -->

How to check Eloquent get() and first() query result

Sunday, March 26, 2017


Every time you run query to the database whether using eloquent get() or first() method, it's always a good idea to check the result of the query before doing other things, make sure the result is as we expected and not returning empty.

The way we check value between eloquent get() method and first() method is different, the eloquent get() will return an object if the query found, so we can check it using isEmpty() method.

Eloquent get() method:

$user = User::where('status', '=', 'active')->get();
if (! $user->isEmpty()) {
// do stuff
}

You can also check using count()
$user = User::where('status', '=', 'active')->get();
if (count($user)) {
// do stuff
}


Eloquent first() method:

If you are using eloquent first() method, check the query using is_object() or empty()
$user = User::where('status', '=', 'active')->first();
if (is_object($user)) {
// do stuff
}

check using !empty()
$user = User::where('status', '=', 'active')->first();
if (!empty($user)) {
// do stuff
}