Skip to content

[13.x] Correctly handle route parameters with defaults and key binding#59128

Draft
alaminfirdows wants to merge 1 commit intolaravel:masterfrom
alaminfirdows:fix/route-default-params
Draft

[13.x] Correctly handle route parameters with defaults and key binding#59128
alaminfirdows wants to merge 1 commit intolaravel:masterfrom
alaminfirdows:fix/route-default-params

Conversation

@alaminfirdows
Copy link

Note
This PR is a follow-up to the previous discussion where @crynobone suggested that the change should be submitted against the master branch instead of the 12.x patch branch.


Description:
This PR fixes an issue where URL::defaults() combined with route parameters (including model key binding fields) causes positional parameter misalignment when generating URLs with route() call.

Problem:
When a route defines a parameter with a key binding (e.g., {team:slug}) and a default is set using only the parameter name (e.g., URL::defaults(['team' => 'example-team']);), the default does not correctly align with the bound field (slug).
As a result, calling route() with positional or named parameters can incorrectly assign values, producing an empty query string like <URL>?team= instead of the expected URL.

Reference: #57488

Solution:
Added a check for both named parameters and key binding fields to correctly align route parameters when generating URLs.

Example:

  1. Define route with model key binding:
Route::get('{team:slug}/projects/{project}', [ProjectController::class, 'show'])
    ->name('projects.show');
  1. Sets default route params from middleware:
URL::defaults(['team' => 'example-team']);
  1. Route Call:
// Case 1: Positional parameter
route('projects.show', 123);

// ❌ Before:
// Exceptions: Missing required parameter for [Route: projects.show] [URI: {team}/projects/{project}] [Missing parameter: project].

// ✅ After:
// http://laravel.test/example-team/projects/123


// Case 2: Named parameters
route('projects.show', ['project' => 123]);

// ❌ Before:
// http://laravel.test/example-team/projects/123?team=

// ✅ After:
// http://laravel.test/example-team/projects/123

@taylorotwell
Copy link
Member

Does it work if you do URL::defaults(['team:slug' => 'foo'])?

@taylorotwell taylorotwell marked this pull request as draft March 9, 2026 14:24
@alaminfirdows
Copy link
Author

Does it work if you do URL::defaults(['team:slug' => 'foo'])?

Yes!

Both URL::defaults(['team:slug' => 'foo']); and URL::defaults(['team' => 'bar']); work perfectly. It also keeps the precedence of the key binding when it is defined in the route.

@taylorotwell
Copy link
Member

No I mean does the current code on 12.x work for you if you just do ['team:slug' => 'foo']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants