这可能是一个微不足道的问题,但我想知道Laravel是否推荐了一种特定的方法来检查从$result = Model::where(…)->get()返回的Eloquent集合是否为空,以及计算元素的数量。

我们目前正在使用!$result来检测空结果,这足够了吗?至于count($result),它实际上涵盖了所有情况,包括空结果吗?


当前回答

我觉得你可以试试

  @if(!$result->isEmpty())
         // $result is not empty
    @else
        // $result is empty
    @endif

或者也可以用

if (!$result) { }
if ($result) { } 

其他回答

in_array()检查数组中是否存在某个值。

public function isAbsolutelyEmpty($value)
{
   return in_array($value, ["", "0", null, 0, 0.0], true);
}

Laravel中给出了几种检查结果计数/检查空/不空的方法:

$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.

我想你正在寻找:

$result->isEmpty()

这与empty($result)不同,后者不会为真,因为结果将是一个空集合。您建议的count($result)也是一个很好的解决方案。我在文件里找不到任何参考资料

我觉得你可以试试

  @if(!$result->isEmpty())
         // $result is not empty
    @else
        // $result is empty
    @endif

或者也可以用

if (!$result) { }
if ($result) { } 

你可以使用:$counter = count($data);