LoginSignup
0
0

More than 1 year has passed since last update.

【Laravelクエリビルダ】where内で変数を用いて期間の条件を絞る方法

Last updated at Posted at 2021-07-10

Laravelのクエリビルダで、whereを用いて対象期間内のデータを取得する方法を解説します。

バージョンは6系です。

ブログで以下のような記事も書いています。

ゴール

期間の開始日と終了日があり、期間内のデータを取得する。

開始日:2021-06-01
終了日:2021-06-29

user_id created_at
1 2021-06-01 12:21:33
2 2021-06-15 15:53:22
3 2021-06-30 09:22:12

user_id created_at
1 2021-06-01 12:21:33
2 2021-06-15 15:53:22

サンプルコード

コントローラー(PostController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;←バージョン8系なら use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        $this->posts = new Post();

        $start = '2021-06-01';
        $end   = '2021-06-29';
        $results = $this->posts->getUser($start, $end);

        return view('posts.index', compact(
            'results',
        ));
    }
}

$start,$endに開始日と終了日をセットし、引数でモデルに変数を渡します。

モデル(Post.php)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;←記述を忘れない

class Post extends Model
{
    public function getUser($start, $end)
    {
      return DB::table('posts')
              ->select('user_id', 'created_at')
              ->where([
                ['created_at', '>=', $start],
                ['created_at', '<=', $end]
              ])
              ->get();
    }
}

モデルにロジックを書きます。

whereで対象期間を指定します。
ちなみに、->whereBetween('created_at', [$start, $end])でも同様の処理ができます。
こっちの方がコンパクトでいいですよ。

ビュー(index.blade.php)

<table>
    <thead>
      <tr>
        <th>日付</th>
        <th>ユーザーID</th>
      </tr>
    </thead>
    <tbody>
    @foreach ($results as $result)
      <tr>
        <td>{{ $result->created_at }}</td>
        <td>{{ $result->user_id }}</td>
      </tr>
    @endforeach
    </tbody>
</table>

スクリーンショット 2021-07-10 13.07.55.png

このようにデータを取得できました。

もし参考になったら忘れずに記事のストックまたはLGTMをお願いいたします。

ブログで以下のような記事も書いています。

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