MWZ

MINDWAREZONE

What is route model binding?

  • Route Model Binding is a feature in Laravel that automatically injects a model instance into a route or controller based on the route parameter.
  • It eliminates the need to manually query the database using methods like find() or where().
  • Laravel automatically returns a 404 response if the model is not found.
  • It makes the code cleaner, shorter, and more readable.

Without Route Model Binding

Route::get('/posts/{id}', [PostController::class, 'show']);
            
public function show($id)
{
    $post = Post::findOrFail($id);

    return view('posts.show', compact('post'));
}
            

With Route Model Binding

Route::get('/posts/{post}', [PostController::class, 'show']);
            
public function show(Post $post)
{
    return view('posts.show', compact('post'));
}
            

How It Works

  • Laravel sees the {post} route parameter.
  • It matches it with the Post $post type-hinted model.
  • It automatically executes something similar to:
Post::findOrFail($id);
            
  • If the record exists, it is injected into the controller.
  • If not, Laravel throws a 404 Not Found exception.

Route Model Binding Using Slug

Post Model

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

Route

Route::get('/posts/{post}', [PostController::class, 'show']);
            

Controller

public function show(Post $post)
{
    return view('posts.show', compact('post'));
}
            

Example URL:

/posts/what-is-laravel
            

Laravel will automatically find:

Post::where('slug', 'what-is-laravel')->firstOrFail();
            

Types of Route Model Binding

Implicit Binding: Laravel automatically resolves the model based on the parameter name and type hint.

Explicit Binding:  You manually define the binding in bootstrap/app.php or a service provider in older versions.