I am querying a model using Laravel Eloquent. When there is records available the query returns a result that is an array of objects.
[{id: 2, num: 3}]
When there is no records available Eloquent returns an array within an array of objects where all the object properties has a null values.
[[{id: null, num: null}]]
The thing is how to I test whether there is no record or a null object. None of the following methods works:
isset($records) // does not cover empty object
!empty($records) // does not seem to see null properties
count($records) > 0 // sees an array more than zero deep
This is my query:
$records = FertilAppUser::select('fertilapp.*')
->leftJoin('fertilapp', 'fertilappuser.id', '=', 'fertilapp.fertilappuser_id')
->where('fertilappuser.id', '=', $request->get( 'id' ))
->groupBy('fertilapp.id')
->orderBy('fertilapp.id', 'asc')
->get();
An empty result must be handled because it is possible and it seems to be the one thing that is a pain to handle for me. Everything works, then I test empty results and boom comes errors!
Can someone help me to understand why the results are arrays of differing depths?
If both results where an array of objects it would be easy but how do I check for !empty($record[0]->id)
and !empty($record[0][0]->id)
without getting an error.
Interestingly the following query returns an array of objects or an array with null [null]
.
$records = DB::select('SELECT fertilapp.* ' .
' FROM fertilapp ' .
' LEFT JOIN fertilappuser ON fertilappuser.id = fertilapp.fertilappuser_id ' .
' WHERE fertilappuser.id = ? ' .
' GROUP BY fertilapp.id ' .
' ORDER BY fertilapp.id ASC ', [$request->get( 'id' )]);
This can the be tested with above methods. Still would like to know why the Eloquent method is returning the result above.
After running the query I check if the results are usable and loop through them.
if (isset($records) && !empty($records) ) {
foreach ($records as $key => $value) {...}
}