コレクションの空をチェックする関数は、isEmpty()、しかし現実では「~が空でないとき」という条件文も良く使います。
もちろん、!if (! $collection->isEmpty()) とすることでも十分なのですが、なぜか if ($collection->isNotEmpty()) の方が私にはわかりやすい。


4年前に、「正しいのはisEmptyでした」という記事を書いたのですが、不思議にもこの記事はとても人気がある記事となっています。過去のトップ10に入っています。今回はこの反対の isNotEmpty() の紹介です。

まず、コレクションでは、

> $users = User::all();
= Illuminate\Database\Eloquent\Collection {#7175
    all: [
      App\Models\User {#7578
        id: 1,
        name: "name",
        email: "test@example.com",
        email_verified_at: null,
        #password: "$2y$10$wIaPHmNNWNtd.MoaR.SQFeiUCk5gAbHylHM4i6TkIh17rbv8US046",
        #remember_token: null,
        created_at: "2023-06-26 21:29:04",
        updated_at: "2023-06-26 21:29:04",
      },
    ],
  }

> if ($users->isNotEmpty()) echo 'ユーザーレコードが存在する';
ユーザーレコードが存在する

文字列のStrオブジェクトでは、

> $str = Str::of('空ではない')
= Illuminate\Support\Stringable {#7575
    value: "空ではない",
  }

> $str->isNotEmpty()
= true

ここで紹介した、HtmlStringのオブジェクトでも

> use Illuminate\Support\HtmlString;
> $html = new HtmlString('<h1>空ではない</h1>');
= Illuminate\Support\HtmlString {#7581
    html: "<h1>空ではない</h1>",
  }

> $html->isNotEmpty()
= true

最後に、エラーなど使用されるMessageBagでも、

> use Illuminate\Support\MessageBag;
> $errors = new MessageBag(['quantity', '数字でありません']);
= Illuminate\Support\MessageBag {#6215}

> $errors->all();
= [
    "quantity",
    "数字でありません",
  ]

> $errors->isNotEmpty()
= true

By khino