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?
This question is related to
laravel
laravel-4
eloquent
laravel-collection
You can use: $counter = count($datas);
According to Laravel Documentation states you can use this way:
$result->isEmpty();
The isEmpty
method returns true
if the collection is empty; otherwise, false
is returned.
I think you are looking for:
$result->isEmpty()
This is different from empty($result)
, which will not be true because the result will be an empty collection. Your suggestion of count($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()
if(count($result)){
...record is exist true...
}
case 2:
if result contain set of multiple row other word using ->get() or ->all()
if($result->count()) {
...record is exist true...
}
There are several methods given in Laravel for checking results count/check empty/not empty:
$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.
You can do
$result = Model::where(...)->count();
to count the results.
You can also use
if ($result->isEmpty()){}
to check whether or not the result is empty.
I agree the above approved answer. But usually I use $results->isNotEmpty()
method as given below.
if($results->isNotEmpty())
{
//do something
}
It's more verbose than if(!results->isEmpty())
because sometimes we forget to add '!' in front which may result in unwanted error.
Note that this method exists from version 5.3 onwards.
so Laravel actually returns a collection when just using Model::all();
you don't want a collection you want an array so you can type set it.
(array)Model::all();
then you can use array_filter to return the results
$models = (array)Model::all()
$models = array_filter($models);
if(empty($models))
{
do something
}
this will also allow you to do things like count()
.
I think you try something like
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
or also use
if (!$result) { }
if ($result) { }
I think better to used
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise, false is returned.
Source: Stackoverflow.com