1 頁 (共 1 頁)

Eloquent collection: counting and detect empty

發表於 : 2017-10-06 09:54:43
yehlu
https://stackoverflow.com/questions/205 ... tect-empty

When using ->get() you cannot simply use any of the below:

代碼: 選擇全部

if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

代碼: 選擇全部

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }