Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

murtaza1904's avatar

How to add prefix to URL in Pest Laravel

I want to add a dynamic prefix to the pest test as we do in Laravel like this

Route::prefix(region())
			->resource('regions', RegionController::class)
            ->except('show')
            ->whereNumber('region');

Now similarly I want to add prefix to my test so that I can test the above route code.

Here is something I want to achieve. I now that in withPrefix method doesn't exist. Is their any similar method for that?

test('index page is loading', function () {
    userLogin();
    
    $response = $this->withPrefix(region())->get(route('regions.index'));

    $response->assertStatus(200);
});
0 likes
6 replies
tykus's avatar

What is the region() function returning?

1 like
murtaza1904's avatar

@tykus Thank you for your response. region() function is only adding string like oc or sandiego. To understand better this is the function code

function region(): ?string
{
    $urlComponents = parse_url(request()->url());

    $path = $urlComponents['path'] ?? null;

    $pathSegments = explode('/', $path);

    return $pathSegments[1] ?? null;
}

Its returning the url first part before / like if the url is

http://127.0.0.1:8000/oc/dashboard

then it returns oc

tykus's avatar
tykus
Best Answer
Level 104

@murtaza1904 your route definition will not work like that... there is no Request (or URL) whenever your Routes get evaluated and cached (in production).

You really need a wildcard segment for the prefix (I use reg here since region will be taken by the ID segment):

Route::prefix({reg})
			->resource('regions', RegionController::class)
            ->except('show')
            ->whereNumber('region');

Then your controller actions will receive a $reg parameter along with any Model-specific $region parameters to identify the model.

1 like
murtaza1904's avatar

@tykus So then only route name works? something like

$response = $this->get(route('regions.index'));
tykus's avatar

@murtaza1904 no; there is a required parameter reg in that case:

$response = $this->get(route('regions.index', ['reg' => 'oc']));
murtaza1904's avatar

@tykus Thank you sir, I got the mistake. I made the changes as you said and its working fine now.

Please or to participate in this conversation.