Use Route Model Binding for Cleaner Controllers

Learn how Laravel's route model binding can automatically inject model instances into your routes, eliminating manual database queries.

1 min readLaravelاقرأ بالعربية

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.

All articles

Keep reading