4
3

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 1 year has passed since last update.

【Laravel】検索機能を実装する(日付期間検索)

Posted at

Laravelでユーザーが打ち込んだ期間の検索を実装したい

画像のようにユーザーが打ち込んだ期間の検索をかけていきます。(いつからいつまでの期間に入力したレコードを表示する形)
※見た目はまだ修正してないので悪しからず。。

スクリーンショット 2023-01-11 20.21.03.png

Controller

class TrRecordController extends Controller
{

    public function index(Request $request) {

        $user_id = Auth::id();
        $from = $request->input('from');
        $until = $request->input('until');
        $part_search = $request->input('part_search');
        $menu_search = $request->input('menu_search');
        $q = TrRecord::query();

        // 全件取得(検索かけなかったら全件表示)
        $query = $q->where('user_id', $user_id)
        ->orderBy('tr_date', 'desc');

        // 日付検索
        if (isset($from) && isset($until)) {
            $query = $q->whereBetween("tr_date", [$from, $until])
            ->where('user_id', $user_id);
        }

        $trRecords = $query->paginate(5);

        return view('trrecords.index', compact('trRecords', 'from', 'until'));

    }

期間の検索をかけたいので、クエリビルダのwhereBetween句を使ってあげます。

whereBetween/orWhereBetween
whereBetweenメソッドは、カラムの値が2つの値の間にある条件を加えます。
$users = DB::table('users')
->whereBetween('votes', [1, 100])
->get();

View

    <form>
        <div>
            <label for="">日付検索</label>
            <input type="date" name="from" placeholder="from_date" value="{{ $from }}">
                <span class="mx-3">~</span>
            <input type="date" name="until" placeholder="until_date" value="{{ $until }}">
        </div>
        <div>
            <button type="submit">検索</button>
        </div>
    </form>

期間の検索なので、input typedateとしてあげます。

以上

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?