Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

route() helper doesn't generate correct URI's for routes with a custom binding key #32201

Closed
elbojoloco opened this issue Apr 2, 2020 · 3 comments · Fixed by #32264
Closed
Labels

Comments

@elbojoloco
Copy link
Contributor

  • Laravel Version: 7.4.0 (since 7.0.0)
  • PHP Version: 7.3.13
  • Database Driver & Version: MySQL 5.7 (MariaDB)

Description:

The route() helper doesn't account for the Laravel 7 way of specifying a custom route model binding key inside the route parameter when passing a Model to use implicit binding. It will generate the URL with ID's as parameters instead of the expected column (like a slug).

Steps To Reproduce:

  1. Create a route like this:
Route::get('/profile/{user:slug}', function (User $user) {
    return $user;
})->name('profile');
  1. Try to generate a URI using the route() helper: route('profile, $user)
  2. Inspect/view the given URI, it should look something like: https://app.test/profile/1 instead of expected: https://app.test/profile/@johndoe (assuming the slug is @johndoe)
@driesvints driesvints added the bug label Apr 2, 2020
@driesvints
Copy link
Member

I'd also expect that to work. Appreciating a PR if you could send one in.

@elbojoloco
Copy link
Contributor Author

elbojoloco commented Apr 2, 2020

@driesvints I tried.. I got it working until I found out that my fix was not compatible with explicitly passing the parameter value (so passing $user->slug instead of $user as route() argument). I will link my commit, maybe someone can use it as inspiration: elbojoloco@d26bec6

Edit:
I'll elaborate a bit more on the problem after my fix.
image
In this image you can see the first bindingField "lucas" being the value that is passed explicitly. The second bindingField is a Post model, because it is passed implicitly. The formatParameterKeys() method in my commit only pulls values from the bindingFields array if the respective param is an instance of UrlRoutable, which is only true for the Post model. As a result the {post} param will try to use the "user" (first bindingField being pulled in this case) key and value "name" to find its route binding key, which will fail and result in it not being bound at all.

@BSN4
Copy link
Contributor

BSN4 commented Apr 6, 2020

you can set it in the model

public function getRouteKeyName()
{
    return 'slug';
} 

or

route('profile, ['slug' => $user->slug])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants