This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from $result = Model::where(...)->get()
is empty, as well as counting the number of elements.
We are currently using !$result
to detect empty result, is that sufficient? As for count($result)
, does it actually cover all cases, including empty result?
There are several methods given in Laravel for checking results count/check empty/not empty:
You can do
to count the results.
You can also use
to check whether or not the result is empty.
I think you are looking for:
This is different from
empty($result)
, which will not be true because the result will be an empty collection. Your suggestion ofcount($result)
is also a good solution. I cannot find any reference in the docs------SOLVED------
in this case you want to check two type of count for two cace
case 1:
if result contain only one record other word select single row from database using ->first()
case 2:
if result contain set of multiple row other word using ->get() or ->all()
I think better to used
I think you try something like
or also use