Home / Snippets / Route Model Binding in Laravel 8
Route Model Binding in Laravel 8 cover

Route Model Binding in Laravel 8

331

3 years ago

2 comments

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}', 'ArticleController@show');

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);
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

A

Alaz

8 months ago

Good snippets!

A

Alaz

8 months ago

Loving the snippet!

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this