6
2

More than 3 years have passed since last update.

【Laravel】Collection型の空値判定 isEmpty()

Last updated at Posted at 2020-12-25

困りごと

PHP歴3ヶ月、Laravel歴1ヶ月の初学者です。LaravelのCollection型の空判定でハマってしまったので、同じような方が減ることを祈って投稿します。下図のように、ある条件で検索を行い、Collection型で返ってきた値に「データが入っているか」or「空」であるかを判定して、表示を分岐をさせる方法についてです。下図のような表示をさせたいという設定で書いています。
flow.png

コレクション型とは?
Object型の一種で、Laravel独自の型でデータベースからデータを取得した際等はこの型になっています。コレクションで利用可>能なメソッドは全部で100個以上あります。メソッドチェーンで記述が可能です。

開発環境

PHP 7.2.34 / Laravel 6.20.5

結論

Collection型の空判定はisEmpty()メソッドが優秀。

controller.php
public function search(Request $request)
    {   
       //バリデーション
       $request->validate([
            'departured_on' => 'required',
            'reverted_on' => 'required|after:departured_on',
        ]);

       //検索
       $searches = Schedule::where(['departured_on','<=',$request->departured_on],
                                    ['reverted_on','>=',$request->reverted_on],
                                    ])->get();
       return view('view',compact('searches'));
    }
view.php
//・・・略
<form action="" method="post">
  @csrf
  <input type="datetime-local" name="departured_on">
  <input type="datetime-local" name="reverted_on">
  <input type="submit" value="検索">
</form>
<div id="output"> 
  @if(isset($searches))   //  検索ボタンの判定(検索ボタンが押された時にtrue) 
     @if($searches->isEmpty()) // 検索条件に合う登録があるか判定(登録があった時にtrue)  
        <p>検索条件に合う登録がありません</p>
     @else
        <table>
           <tr>
              <th>出発日</th>
              <th>返却日</th>                     
           </tr>
           @foreach ($searches as $search)
           <tr>
              <td>{{$search->departured_on}}</td>
              <td>{{$search->reverted_on}}</td>
           </tr>
           @endforeach 
        </table>
     @endif
   @else  //  検索ボタンの判定(検索ボタンが押されていない時)
     <p>検索してください</p>
   @endif
 </div>

この例では、コントローラーから返ってきた値がもしも空であれば「検索条件に合う登録がありません。」、データが入っていればデータを表示します。このような空判定をする際には isEmpty()メソッド を用います。if($var),isset($var),empty($var),is_null($var)では判定できません。コントローラーから渡された値はCollection型であるためです。
公式ドキュメントにもCollection型の空判定にはisEmpty()メソッドを使うように書かれています。
https://laravel.com/docs/5.6/collections#method-isempty

The isEmpty method returns true if the collection is empty; otherwise, false is >returned:

collect([])->isEmpty(); // true

最後に

コレクション型についての理解が甘く、私は3時間ほどハマってしまいました。
また、is,isset,empty,null,""などの空判定は初学者にとっては少し理解が難しい部分だと思います。
これらを再度復習し、この記事の厚みも今後増やしたいと思います。
(もしこの記事に誤りがありましたらご教授いただけると幸いです。)

6
2
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
6
2