LoginSignup
1
1

More than 1 year has passed since last update.

Laravelでチェックボックスを使用した検索フォームの作り方

Last updated at Posted at 2022-03-20

サンプル

検索画面

image.png

検索結果画面

image.png

コード

ルーティング処理

\routes\web.php
Route::get('/search/','Search\SearchController@index');
Route::post('/search/result/','Search\SearchController@result');

コントローラー

  • index: 検索画面の処理
  • result: 検索結果画面の処理
\app\Http\Controllers\Search\SearchController.php

<?php


namespace App\Http\Controllers\Search;

use DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SearchController extends Controller
{
    public $form_data = [
        ['名前', 'checkbox[name]', 'name'],
        ['メールアドレス', 'checkbox[email]', 'email'],
        ['コメント', 'checkbox[comment]', 'comment'],        
    ];

    public function index()
    {
        return view('search/index',[
            'form_data' => $this->form_data,
        ]);
    }

    public function result(Request $request)
    {

        $validation_array = [
            'keyword' => 'required',
            'checkbox' => 'required',
        ];

        $validator = Validator::make($request->all(), $validation_array);

        if ($validator->fails()) {
            return redirect('/search/')
                        ->withErrors($validator)
                        ->withInput();
        };

        $checkbox_arrary = [];
        foreach ($request->input('checkbox') as $value){
            $checkbox_arrary[] = $value;
        }

        $user_data = DB::table('users');

        if(in_array('name', $checkbox_arrary)){
            $user_data->where('name', 'like', '%'.$request->input('keyword').'%');
        }
        if(in_array('email', $checkbox_arrary)){
            $user_data->where('email', 'like', '%'.$request->input('keyword').'%');
        }
        if(in_array('comment', $checkbox_arrary)){
            $user_data->where('comment', 'like', '%'.$request->input('keyword').'%');
        }

        $result = $user_data->get();

        return view('/search/result',[
            'search_data' => $result,
        ]);
    }

}


View

\resources\views\search\index(.blade).php
<form method="POST" action="/search/result">
    <table>
        <tr>
            <th>検索カテゴリ</th>
            @foreach($form_data as $value)
                <td>
                    <input name="{{ $value[1] }}" type="checkbox" value="{{ $value[2] }}" {{ old($value[1]) == $value[2] ? 'checked' : '' }}>
                    <p>{{ $value[0] }}</p>
                </td>
                @if($errors->has('checkbox'))
                    <p style="color: red;">{{ $errors->first('checkbox') }}</p>
                @endif 
            @endforeach                               
        </tr>
        <tr>
            <th>検索ワード</th>
            <td><input name="keyword" type="text" value="{{ old('keyword') }}"></td>
            @if($errors->has('keyword'))
                    <p style="color: red;">{{ $errors->first('keyword') }}</p>
            @endif 
        </tr>
        <tr>
            <button type="submit">検索する</button>
        </tr>
    </table>
    @csrf
</form>
\resources\views\search\result(.blade).php
<div>
    <table>
        <tr>
            <th>名前</th>
            <th>メールアドレス</th>
            <th>コメント</th>                                
        </tr>
        @foreach($search_data as $value)
        <tr>
            <td>{{ $value->name }}</td>
            <td>{{ $value->email}}</td>
            <td>{{ $value->comment }}</td>
        </tr>
        @endforeach
    </table>
    <a href="/search/">検索画面に戻る</a>
</div>

ポイント

チェックボックスのバリデーション

\resources\views\search\index(.blade).php
// foreachでデータが渡された後
<input name="checkbox[name]" type="checkbox" value="name" {{ old(checkbox[name]) == 'name' ? 'checked' : '' }}>
<input name="checkbox[email]" type="checkbox" value="email" {{ old(checkbox[email]) == 'email' ? 'checked' : '' }}>
<input name="checkbox[comment]" type="checkbox" value="comment" {{ old(checkbox[comment]) == 'comment' ? 'checked' : '' }}>

inputname属性では、 checkbox[name]のように配列で値を指定できる。

\app\Http\Controllers\Search\SearchController.php
$validation_array = [
    'keyword' => 'required',
    'checkbox' => 'required',
];

配列名をrequiredすることで、チェックボックスのどれかにはチェックを入れること をバリデーションできる。

検索処理

\app\Http\Controllers\Search\SearchController.php
$checkbox_arrary = [];
foreach ($request->input('checkbox') as $value){
    $checkbox_arrary[] = $value;
}

$request->input('checkbox[name]') みたいな形で値を取り出せないので、$request->input('checkbox')foreachにかけて別の配列に入れ直して、この後の処理で使えるようにする。

\app\Http\Controllers\Search\SearchController.php
$user_data = DB::table('users');

if(in_array('name', $checkbox_arrary)){
    $user_data->where('name', 'like', '%'.$request->input('keyword').'%');
}
if(in_array('email', $checkbox_arrary)){
    $user_data->where('email', 'like', '%'.$request->input('keyword').'%');
}
if(in_array('comment', $checkbox_arrary)){
    $user_data->where('comment', 'like', '%'.$request->input('keyword').'%');
}

$result = $user_data->get();

どのチェックボックスに値が入っていたかでif文をかけ、DBクエリでwhereを追加している。
最後にget()することを忘れない。

参考記事

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