在使用Laravel Eloquent
模型時,我們可能要判斷取出的結果集是否為空,但我們發現直接使用is_null
或empty
是無法判段它結果集是否為空的。
var_dump之后我們很容易發現,即使取到的空結果集, Eloquent
仍然會返回Illuminate\Database\Eloquent\Collection
對象實例。
其實,Eloquent
已經給我們封裝幾個判斷方法。
$result = Model::where(...)->get();
//不為空則
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
參考網站:http://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty
轉自:http://douyasi.com/laravel/eloquent_collection_detect_empty.html