Posts Learn Components Snippets Categories Tags Tools 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

189 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);
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Route Model Binding in Laravel 8

)