LoginSignup
5
2

More than 3 years have passed since last update.

Laravel 検索フォームとページネーション連携

Posted at

一覧ページ(index.blade.php)に実装することを想定
ここでは標準で用意されているuserテーブルの検索を実装する

  1. viewファイル(blade)にフォームを追加する
  2. controller(UserController.php)に検索処理とページネーション処理を実装する

Viewファイルの修正

検索条件を保持するためinputのvalueに$nameを追加

index.blade.php
...(略)...
      <form action="{{ url('users/') }}" method="get">
        @method('GET')
        @csrf
        <div class="form-group row">
          <label for="searchName" class="col-sm-2 col-form-label">{{ __('Name') }}</label>
          <div class="col-sm-10">
            <input type="text" class="form-control @if (!empty($errors->first('name'))) is-invalid @endif" id="name" name="name" value="{{ old('name', $name ?? '') }}" placeholder="{{ __('Name') }}">
            @error('name')
              <span class="invalid-feedback" role="alert"><strong>{{ $errors->first('name') }}</strong></span>
            @enderror
          </div>
        </div>
        <div class="form-group row">
          <div class="offset-sm-2 col-sm-10">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search mr-1"></i>{{ __('Search') }}</button>
          </div>
        </div>
      </form>
...(略)...

これでアクションusers.indexのGETメソッドがリクエストパラメータ付きで呼ばれる

コントロール修正

index()の引数にRequestを追加する。
$query->paginate(10)でページネーション付きのユーザー一覧情報になる。
retunでviewに検索条件も渡す。

UserController.php
public function index(Request $request)
{
    $name = $request->input('name');
    $query = User::query();
    if (!empty($name)) {
         $query->where('name', 'like', '%' . $name . '%');
    }
    $users = $query->paginate(10);
    return view('users.index', compact('users', 'name'));
}

ページネーション連携

通常は$users->links()だが、メソッドappends(['name' => $name ?? ''])を追記する

index.blade.php
...(略)...
  {{ $users->appends(['name' => $name ?? '' ])->links() }}
...(略)...
5
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
5
2