Home API Tools Posts Hire Me About
Sign In Create Account
Laravel

Use Route Model Binding for Cleaner Controllers

December 09, 2025 1 min read 79 views

Instead of manually fetching models in your controller, Laravel can do it automatically:

Before (Manual Query)

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

After (Route Model Binding)

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

Laravel automatically finds the Post by ID and returns 404 if not found. You can also use custom keys:

// In your model
public function getRouteKeyName()
{
   return 'slug';
}

Now /posts/my-post-slug will automatically resolve using the slug column.

Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!