3
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?

More than 5 years have passed since last update.

GetでQuery(Parameter)を渡す方法

Last updated at Posted at 2019-12-03

getqueryを渡す方法

タイトルを見て、「そんなことも分からんのか」と思う方もいらっしゃると思います。
そうなんです、私はできなかったんです。

以下では、Laravel プロジェクトでシステム開発をしているときの
私の失敗と解決できた方法を記載していきます。

HTTP テスト

正しく動作するかをテストすることはとても重要です。

私もシステムが正しく動作するか、テストを書いており
検索機能が正しく動作しているか HTTP テストを書いていた時の話です。

テストの作成

よし、テストを作成するぞと意気込んで作成を開始しました。

まず、プロジェクトフォルダで、ターミナルを開きます。

$ cd test // 現在の階層のtest(フォルダ)に移動する

そして、ItemSearchTestを作成します。

$ php artisan make:test ItemSearchTest

これでtest\Feature\ItemSearchTest.phpが生成されます。
さぁテストを書いていきましょう。

queryが渡せない

文字列検索は、getメソッドで自己参照させてqueryで条件を与えていました。
そのため、以下のようなコードを書きました。

test\Feature\ItemSearchTest.php
public function testGeneralPattern () {
    $query = [
        "keyword" => "〇〇",
    ];

    $response = $this->get(route("item"),[
            "query" => $query,
    ]);
}

実行してみると、NG のパターンが通らない。

中身を調べてみると、queryはまったく送られていませんでした
ネットで調べた通りにHeaderの中に入れたのになぁ、と途方に暮れることになりました。

URL でもダメ

他に方法はないかと考えた結果、URL にquery情報を入れ込む方法を試してみました。

test\Feature\ItemSearchTest.php
public function testGeneralPattern () {
    $url = "http://localhost/item?keyword=〇〇";

    $response = $this->get($url);
}

これでもダメでした。
この時点で少し心は折れかけていました。

route()

長時間悩まされていましたが、解決のときが来ました。
route()の第二引数でqueryが渡せる」 という情報を手に入れたのです。

早速、試してみました。

test\Feature\ItemSearchTest.php
public function testGeneralPattern () {
    $query = [
        "keyword" => "〇〇",
    ];

    $response = $this->get(route("item", $query);
}

頼む!通ってくれ!!と願いを込めて、・・・・

ちゃんとqueryが渡せていました!

今月で一番ホッとした瞬間でした。

自己参照でqueryを引き継ぐ

検索機能だけでなく、ソート機能やタブ切替など
機能が増えてくると、現在のqueryを保持して自己参照したいと考えました。

上記でもあるように、route()を使えばqueryを渡せることは分かっています。
あとは現在のqueryを取得する方法だけです。

Request::query()

現在のqueryを配列で取得するものです。
これが手に入ればあとはもう簡単でした。

resources\views\item\index.blade.php
<a href="{{ route('item', array_merge(Request::query(), ['tab' => '〇〇'])) }}">〇〇</a>

これで現在のqueryに与えたいqueryを追加した URLとなります。

3
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
3
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?