1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで50項目以上の検索条件を動的に扱う方法

Posted at

Laravelで50項目以上の検索条件を動的に扱う方法

  • 「画面からめちゃくちゃいっぱい条件が飛んでくる」
  • 「テーブルも1個じゃなくて、複数にまたがってる」
  • 「でも現場ルールで全部コントローラに書いてって言われる…」
    そんな要件、ありますよね。
    そんなときに役立つ、検索条件を定義的に書いて、動的SQLを組み立てる方法を紹介します。

この記事でやること

  • 入力された検索条件だけでSQLを動的に組み立てたい
  • 条件は50項目以上あっても対応したい
  • 検索対象のカラムは複数テーブルにまたがる
  • 全部コントローラに書く現場ルールを守りたい

ポイントはこれだけ!

✔ 条件の「定義」と「処理」を分ける
✔ 条件は配列で定義して foreach で回す
✔ LIKEとか>=とかは定義に入れちゃう
✔ JOIN使えば他テーブルもいける
✔ 空欄の条件は無視してOK!

実装サンプル(全部コントローラ内)

public function search(Request $request)
{
    $query = DB::table('users')
        ->join('profiles', 'users.id', '=', 'profiles.user_id');

    // 条件をまとめてここで定義
    $conditionsMap = [
        'name'        => ['column' => 'users.name', 'operator' => 'like'],
        'email'       => ['column' => 'users.email', 'operator' => 'like'],
        'age_min'     => ['column' => 'profiles.age', 'operator' => '>='],
        'age_max'     => ['column' => 'profiles.age', 'operator' => '<='],
        'phone'       => ['column' => 'profiles.phone', 'operator' => 'like'],
        'gender'      => ['column' => 'profiles.gender', 'operator' => '='],
        'status'      => ['column' => 'users.status', 'operator' => '='],
        'created_from'=> ['column' => 'users.created_at', 'operator' => '>='],
        'created_to'  => ['column' => 'users.created_at', 'operator' => '<='],
        // さらに40項目以上追加可能
    ];

    //  入力されてる条件だけで検索する
    foreach ($conditionsMap as $key => $rule) {
        $value = $request->input($key);

        if ($value === null || $value === '') continue;

        $operator = $rule['operator'];
        $column = $rule['column'];

        $query->where($column, $operator, $operator === 'like' ? "%{$value}%" : $value);
    }

    //  必要なカラムだけ取ってくる
    $results = $query->select('users.*', 'profiles.phone')->get();

    return view('search.results', compact('results'));
}

🤔 これの何が良いの?
✅ どの条件が何のカラムに対応してるかが一覧で見える

✅ 条件が1つ増えても「定義を1行追加」するだけ

✅ コントローラ内だけで完結!現場ルールも守れる!

✅ 50項目あっても検索条件部分はコンパクト!

✅ 空欄は無視するので、気軽に使える!

まとめ

検索項目がめちゃくちゃ多い、テーブルも複数ある、でもコントローラ内に全部書けって言われる…。
そんな時は、この「条件を定義にまとめて、ループで処理するスタイル」が便利でした。

このパターン、ぜひ使ってみてください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?