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.