Posts Learn Snippets Categories Tags About
/

Route Model Binding in Laravel 8

Learn how to get modal using other than the id column in Laravel 8

Created on Jun 26, 2021

17 views

In Laravel, you can override the route key for the modal by using the "getRouteKeyName" method. Instead of the default "id" you can now specify to use your preferred column such as "slug" or another column identifier that you have set.

Inside your "App\Models\[your-modal].php" modal define the "getRouteKeyName".
# App\Models\Article.php

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

In your route specify the "article" as the key and by doing so Laravel will use the "slug" key to implicitly retrieve the instance.
# routes/web.php

Route::get('/article/{article}', '[email protected]');

In the controller, specify the "article" as the key and type hint in the model instance.
# App\Http\Controllers\ArticleController.php

public function show(Article $article)
{
    dd($article);
}

Before
# App\Http\Controllers\ArticleController.php

public function show($id)
{
    $article = Article::find($id);

    dd($article);
}

After
# App\Http\Controllers\ArticleController.php

public function show(Article $article)
{
    dd($article);
}

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.