tighten / ziggy

Use your Laravel routes in JavaScript.
MIT License
3.83k stars 247 forks source link

Default route parameters are not populated in Laravel redirects #699

Closed tiagocpeixoto closed 7 months ago

tiagocpeixoto commented 7 months ago

Ziggy version

1.8.1

Laravel version

10.38.2

Description

I defined a Laravel route based on a tenant prefix:

Route::get('/{tenant}/dashboard', [DashboardController::class, 'show'])->name('dashboard');

And then I created a middleware to redirect to the correct tenant if the user enters one that they are not authorized to access. The middleware does something like this:

URL::defaults(['tenant' => $tenantId]);
return redirect()->route('dashboard');

When the redirect is complete, the React SPA throws the following exception: error: Ziggy error: 'tenant' parameter is required for route 'dashboard'.

But if a change the redirect to:

URL::defaults(['tenant' => $tenantId]);
Inertia::location(route('dashboard'));

then no error occurs.

In the React client, the link is:

<Link href={route("dashboard")}>Users</>

It seems that redirects with Inertia::location update the Ziggy state (???) and correctly populate the default parameters, but this is not the case with redirect()->route(...).

IF the redirect is done with redirect()->route('dashboard'), the workaround on the React side is to explicitly set the expected param:

<Link href={route("dashboard", {tenant})}>Users</>

In this case, the tenant param was obtained from the usePage hook (Ziggys defaults !!!), which demonstrates that the default (tenant) parameter is being loaded on the client:

const { ziggy: { defaults: { tenant } } } = usePage().props;

So is it a bug or a misunderstanding in using the default parameters?

Thanks in advance for your help and thanks again for the wonderful package!

Ziggy call and context

As explained in the description.

Ziggy configuration

As explained in the description.

Route definition

As explained in the description.