LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】コレクション型の空値

Posted at

はじめに

 LaravelのEloquentを用いてgetメソッドやfirstメソッドで値を取得すると戻り値はCollection型になります。値がある時とない時で条件分岐させようとしてもemptyやissetなどでは判定ができません。

isEmptyメソッド

 Collection型の空値の判定にはisEmptyメソッドを使います。
公式ドキュメントを見てみましょう。

isEmptyメソッドはコレクションが空の場合にtrueを返します。そうでなければfalseを返します。

実際には下記のように使います。

controller.php
public function judge()
{
  $user_id = \Auth::id();
  $comments = Comment::where('user_id',$user_id)->get();
  return view('view',compact('comments'));
}
view.php
  //・・・略
  @if($comments->isEmpty())
     <p>コメントがないとき・・・</p>
  @else
          <p>コメントがあるときーー!!</p>
  @endif

これで、\$commentsにデータがなければ、if文の中身が、あればelse文の中身が表示されます。

終わりに

 公式ドキュメント最強!

0
0
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
0
0