Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing Route Key Name not working

Tags:

laravel

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

like image 257
Ali Sherafat Avatar asked Feb 02 '17 15:02

Ali Sherafat


Video Answer


1 Answers

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';
}
like image 93
Denis Priebe Avatar answered Dec 05 '22 13:12

Denis Priebe