1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Carbonを用いて期間検索機能を作る

Posted at

はじめに

日付検索する時にDBには年月日時分秒まで登録されているけど期間(年月日)で検索したい時ありませんか。
そんな時はCarbonを使って検索機能を作りましょう。

Carbonを用いて期間検索機能を作る

ある事柄が始まった日時$period[start_at]の検索で、検索期間(年月日)のはじめを$request['start_at_from']、検索期間(年月日)の終わりを$request['start_at_to']として$requestの配列で受け取ったとします。

$period['start_at_from']$period['start_at_to']は(2020-08-13のように)年月日で受け取っているとしてCarbonを用いて00:00:00と日時分を仮置きします。

//2020-08-13
$period['start_at_from']
//2020-08-13 00:00:00
Carbon::parse($period['start_at_from'])

startOfDay()メソッドで1日の中の一番初めの時刻(00:00:00)、endOfDay()メソッドで1日の中の一番終わりの時刻(23:59:59)を取得できます。

//2020-08-13 00:00:00
Carbon::parse($period['start_at_from'])->startOfDay());
//2020-08-13 23:59:59
Carbon::parse($request['start_at_to'])->endOfDay()); 

whereは第一引数にカラム名、第二引数に比較演算子、またはSQLで使うオペレータ、第三引数に比較する値を指定します。
上記までのものも合わせて下記に実装をまとめます。

Controller.php
use Carbon\Carbon;

public function periodSearch(Request $request)
{
    $inputs = $request->validatedValues();
    
    $this->where('start_at', '>=', Carbon::parse($request['start_at_from'])->startOfDay()); 
    $this->where('start_at', '<=', Carbon::parse($request['start_at_to'])->endOfDay()); 
         } 

return view('periodSearch', ['period'=> $period]);

おわりに

Carbonは日時を操作するのに大変便利なので使いこなせるようにCarbonはどんなことができるか調べておくと良いかもしれません。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?