Eloquent collection: counting and detect empty

http://laravel.com/

http://kejyun.github.io/Laravel-4-Docum ... roduction/
回覆文章
yehlu
Site Admin
文章: 3245
註冊時間: 2004-04-15 17:20:21
來自: CodeCharge Support Engineer

Eloquent collection: counting and detect empty

文章 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)) { }
回覆文章

回到「laravel」