LARAVEL

Laravel Route Model Binding Complete Guide

February 5, 2024 12 min read

Introduction

Route Model Binding in Laravel provides a convenient way to automatically inject Eloquent models directly into your route controllers. Instead of manually fetching models, Laravel resolves them based on the route parameters.

Implicit Binding

Laravel automatically resolves Eloquent models based on the variable name:

// routes/web.php
Route::get('/posts/{post}', function (Post $post) {
    return $post;
});

The {post} segment automatically fetches the Post model with matching ID:

// Model: app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'author_id'];
    
    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }
}

If the model isn't found, a 404 is automatically returned.

Explicit Binding

Register explicit bindings in your RouteServiceProvider:

// app/Providers/RouteServiceProvider.php
public function boot()
{
    Route::model('post', Post::class);
    
    // Or with custom resolution
    Route::bind('post', function ($value) {
        return Post::where('slug', $value)->firstOrFail();
    });
    
    parent::boot();
}

Custom Key Resolution

Use a different column for model resolution:

// Use 'slug' instead of 'id'
Route::get('/posts/{post:slug}', function (Post $post) {
    return $post;
});

Or override the getRouteKeyName in your model:

// app/Models/Post.php
class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

Route Scoping

Automatically scope nested routes:

// Parent-child model binding
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    // $post is automatically scoped to $user
    return $post;
})->scopeBindings();
// Or define in route group
Route::prefix('/users/{user}')->scopeBindings()->group(function () {
    Route::get('/posts/{post}', function (Post $post) {
        return $post;
    });
});

Summary

Route Model Binding is one of Laravel's most powerful features, enabling clean controller code and automatic model resolution. By leveraging implicit and explicit binding, you can build elegant and maintainable routes.

For more information, check out our other tutorials on Resource Routes and Form Request Validation.