0
0
LaravelHow-ToBeginner · 3 min read

How to Use Route Model Binding in Laravel: Simple Guide

In Laravel, route model binding automatically injects model instances into your route parameters by matching the ID or custom key. You define it by type-hinting the model in your route or controller method, and Laravel fetches the model for you.
📐

Syntax

Route model binding works by type-hinting a model class in your route or controller method parameter. Laravel then fetches the model instance that matches the route parameter.

Example parts:

  • {user}: route parameter
  • User $user: type-hinted model in method
  • Laravel matches {user} to $user and fetches the model by ID
php
Route::get('/users/{user}', function (App\Models\User $user) {
    return $user;
});
💻

Example

This example shows a route that uses route model binding to fetch a User model by its ID from the URL and returns the user data.

php
<?php

use Illuminate\Support\Facades\Route;
use App\Models\User;

Route::get('/users/{user}', function (User $user) {
    return response()->json([
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email
    ]);
});
Output
{ "id": 1, "name": "John Doe", "email": "john@example.com" }
⚠️

Common Pitfalls

1. Missing type hint: If you don't type-hint the model, Laravel won't perform model binding.

2. Route parameter name mismatch: The route parameter name must match the variable name in the method.

3. Model not found: If no model matches the ID, Laravel throws a 404 error automatically.

php
<?php
// Wrong: parameter name does not match
Route::get('/users/{user}', function (App\Models\User $profile) {
    return $profile;
});

// Right: parameter name matches
Route::get('/users/{user}', function (App\Models\User $user) {
    return $user;
});
📊

Quick Reference

ConceptDescription
Route parameterThe placeholder in the URL, e.g. {user}
Type hintThe model class in the method parameter, e.g. User $user
Automatic fetchingLaravel fetches the model by ID or custom key
404 handlingIf model not found, Laravel returns 404 automatically
Custom keysOverride getRouteKeyName() in model to bind by other fields

Key Takeaways

Type-hint the model in your route or controller method to enable route model binding.
Ensure the route parameter name matches the method parameter name exactly.
Laravel automatically returns a 404 error if the model instance is not found.
You can customize the key used for binding by overriding getRouteKeyName() in your model.
Route model binding simplifies fetching models and reduces boilerplate code.