LaravelのCollectionが空かどうか判定するとき


地味なミスをしていたので備忘録。

失敗ケース

isset($collection), empty($collection)
などでは判定ができません。

試しに

{{ var_dump($collection) }}

とするとわかりますが、

object(Illuminate\Database\Eloquent\Collection)#1533 (1) { ["items":protected]=> array(0) { } }

これはただの配列ではなく、 Collectionですもんね。
当たり前のことを忘れていました。

調整

ちゃんとisEmpty()というCollectionのメソッドを使います。
https://laravel.com/docs/8.x/collections#method-isempty

$collection->isEmpty()

余談
Collectionのメソッドとプロパティ多すぎるですぜ...!