LoginSignup
2
3

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-07-01

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

失敗ケース

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のメソッドとプロパティ多すぎるですぜ...!

スクリーンショット 2021-07-01 10.24.28.png

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3