I'd like model binding to use a table column other than id
when retrieving a given model, and I override getKeyName
in Model class (Service
in this case) but it's not working!
class Service extends Model{
//override
public function getRouteKey() {
return 'key';
}
}
Service table:
id | key(string,unique) | name(string)
my routes file:
Route::resource('services', 'ServiceController');
and in ServiceController
:
public function show(Service $service) {
return $service;
}
but when I go to mysiteurl.com/services/vps
it shows the 404 page.
(mysiteurl.com/services/1
works but I don't want to use id column in URL)
Laravel docs
If you want Laravel to bind your model to a route with a value other than the model's ID, you need to override the getRouteKeyName()
method like so:
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With