0
0

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 FormファサードにてGETリクエストのクエリパラメーター設定するときの注意点

Posted at

概要

古いlaravelやlaravel collectivだとBladeで使えるFormファサードにて、GETリクエストのクエリパラメーターを設定する際にめっちゃ詰まったので方法をまとめておく。

前提

クエリパラメーターを追加する前のbladeのコードを下記に記載する。

hoge.blade.php
<div>
    {{ Form::open(['route' => ['hoge.index'], 'method' => 'GET']) }}
    {{ Form::input('text', 'search_word', null, []) }}
</div>
<div>
    <a>
        <button>
            検索する
        </button>
    </a>
</div>
{{ Form::close() }}

結論

FormファサードでGETリクエストのクエリパラメーターを設定したい場合はForm::hidden('キー名', 値)を使って指定する。
fuga_id=1をクエリパラメーターに設定したい場合は下記のように設定する

hoge.blade.php
<div>
    {{ Form::open(['route' => ['hoge.index'], 'method' => 'GET']) }}
    {{ Form::input('text', 'search_word', null, []) }}
    {{ Form::hidden('fuga_id', 1 }}
</div>
<div>
    <a>
        <button>
            検索する
        </button>
    </a>
</div>
{{ Form::close() }}

詰まったこと

ルートネームを使ってリンク先を指定し、クエリパラメーターを設定する場合は下記のようにする。

hoge.blade.php
<a href="{{ route('hoge.index', ['fuga_id' => 1]) }}">

上記のように記載するとルートネームでURLパスが解決され末尾に?fuga_id=1が設定される。
自分はFormファサードを使う場合も同様だと考え、下記の様にコードを修正していた。

hoge.blade.php
<div>
    {{ Form::open(['route' => ['hoge.index', 'fuga_id' => 1], 'method' => 'GET']) }}
    {{ Form::input('text', 'search_word', null, []) }}
</div>
<div>
    <a>
        <button>
            検索する
        </button>
    </a>
</div>
{{ Form::close() }}

ただ、この方法だとsearch_wordのクエリパラメーターは設定されるがfuga_idのクエリパラメーターは設定されない。
下記の個々の状態でクエリパラメーターを確認したがfuga_idのクエリパラメーターは確認できない。

  • リクエストを受け取ったコントローラーでバリデーションチェックのために使っているリクエストクラス(HogeRequest)の内容を確認
  • リクエストを受け取ったコントローラーでデフォルトのリクエストクラス(Request)の内容を確認
  • リバプロのnginxのリクエストログの内容を確認

ただ逆に先に紹介したコードでレンダリングされた画面をchromeを使ってコードを確認すると生成されたformタグのactionのURLに?fuga_id=1のクエリパラメーターが付与されたURLが設定されている。
そのためどこでクエリパラメーターが消失したのかが分からず詰まった。原因はそもそものコーディングミス。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?