LoginSignup
11
7

More than 3 years have passed since last update.

Laravel6 検索フォーム (GET) パラメータを取得できない時の対処法

Posted at

この記事は、Laravel6において検索時にGETメソッドのパラメータを取得できない時の対処法です。

環境

macOS
Laravel 6.20.3
Doeker 19.03.13

Eventテーブルにあるtitleカラム(string型)を検索します。一致する場合それを返し、一致しない場合はEventの全てのカラムを返します。

解決する前

検索機能に関係あるところだけ書いています。

event/index.blade.php
<div class="container">
  <div class="row">
  <form action="{{url('/event')}}" method="GET">
    <input type="text" name="search" value="{{ $search }}" placeholder="イベント名を入力してください">
    <input type="submit" value="検索">
  </form>
  </div>
</div>
EventController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event;

public function index(Request $request)
    {   

        $search = $request->input('search');
        if (!empty($search)){
            $events = Event::where('title',$search)->orderBy('created_at','desc')->get();
        }else{
            $events = Event::orderBy('created_at','desc')->get();
        }
        return view('event.index',compact('events'));
}
wep.php
Route::resource('event', 'EventController');

formのGETメソッドを使いパラメータをcontrollerに渡しています。
しかしパラメータは空になりelse文ですべてのEventが返ってしまい検索ができませんでした。
(ちなみにcontrollerの一行目にdd($request)を追記することでパラメータは確認できます。)

解決方法

index.blade.phpを以下のように修正します。

index.blade.php
 <form action="{{ route('event.index') }}" method="post">  
      {{ csrf_field()}}  
      {{method_field('get')}}
      <input type="search" name="search" placeholder="イベント名を入力してください">
      <input type="submit" value="検索">
 </form>

formの方をpostにして、{{method_field('get')}}でメソッドをgetにしています。
この方法で無事にパラメータが渡り、検索できるようになりました。

Laravelのバージョンによっては解決前の書き方でできるみたいなので、環境に合わせて色々試してみてください。

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