1
1

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 1 year has passed since last update.

[Laravel][PHPUnit]パスパラメータとクエリパラメータの渡し方

Posted at

したいこと

PHPUnitでパスパラメータとクエリパラメータを両方渡したい

前提

ルーティングとコントローラーは適当です。

ルーティング
Route::get('/user/{user_id}/{hogehoge}', [UserController::class, 'show'])->name('user.fugafuga');
コントローラー
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    /**
     * 指定ユーザーのプロファイルを表示
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($userId, $hogehoge, $queryParameters)
    {
        return view('user.profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

解決

テスト
$queryParameters = [
    'name' => '太郎',
    'age' => 18
];

$response = $this->get(route(user.fugafuga, [
    'user_id' => 1,
    'hogehoge' => 'aiueo',
    ...$queryParameters
]));

このテストで発行されるURL(一部省略)は以下

URL
.../user/1/aiueo?name=太郎&age=18

まとめ

解決してみると意外と簡単な書き方だった。
備忘録も兼ねて記事に残しておく。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?