0
0

More than 3 years have passed since last update.

51歳からのプログラミング 備忘 Laravel 日付でデータ検索

Last updated at Posted at 2019-12-27
html
<?php
  $date = new DateTime();
  $date = $date->format('Y-m-d');
?>

<form name="sample" action="sample" method="post">
   {{ csrf_field() }}
      開始日<input type="date" name="start" value="{{$date}}">
      至 日<input type="date" name="end"   value="{{$date}}">

     <button>送信</button>
</form>


<input type="date">の日付型は、yyyy/MM/dd ( 2019-12-24 )という表示形式。

なのでPHPでフォーマットを合わせてます('Y/m/d')

controller
public function sample(Request $request){
  $form  = $request->all();
  if(!empty($form)){
      $start = date('Y/m/d 00:00:00',strtotime($form['start']);
      $end   = date('Y/m/d 00:00:00',strtotime($form['end']);
  }
}

if(empty($start)){ $start = '1970-01-01 00:00:00'; }
if(empty($end)  ){ $end   = '9999-12-31 23:59:59'; }

$sample = Sample::whereBetween('created_at',[$start,$end]);
if(!empty($form))について

で送信されるデータがNULLだったとしても、formデータは配列で送られるので、配列データは中身なしで送られる。なのでを空送信しても、

isset($form) = true
となってしまう。


配列が空であることを確認するのは、emptyを使いましょう。emptyで

を空送信すると

!empty($form) = false
になってくれます。


日付の調整(00:00:00)

日付検索する場合に、
whereBetween('created_at',['2019-12-24','2019-12-24'])としてしまうと検索されない。
whereBetween('created_at',['2019-12-24 00:00:00','2019-12-24 23:59:59']としよー。

忘れるな!俺!

0
0
1

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