🔗 Route Model Binding in Laravel
Route Model Binding automatically injects model instances into your route or controller, simplifying code and improving readability.
📘 What is Route Model Binding?
Instead of manually retrieving models using IDs from route parameters, Laravel will automatically fetch the correct model instance based on the ID in the URL.
✅ Implicit Model Binding
Laravel automatically resolves Eloquent models if the route parameter name matches the variable name in the method and is type-hinted with the model class.
// routes/web.php
use App\Models\User;
Route::get('/user/{user}', function (User $user) {
return $user->name;
});
If the URL is /user/5, Laravel will fetch User::find(5) automatically.
{user} must match the variable name $user in the closure or controller.
🔑 Binding by Custom Field
If you want to bind using a custom field (e.g., slug instead of id):
// In your model (e.g., Post.php)
public function getRouteKeyName()
{
return 'slug';
}
// routes/web.php
Route::get('/post/{post}', function (Post $post) {
return $post->title;
});
This will now use Post::where('slug', $value)->first().
🛡️ Auto 404 Handling
If the model is not found, Laravel automatically returns a 404 error — no extra checks needed.
📌 Explicit Binding
Define binding logic in RouteServiceProvider if you want to customize how a model is resolved:
// app/Providers/RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('user', User::class);
// or use Route::bind for custom logic
Route::bind('user', function ($value) {
return User::where('username', $value)->firstOrFail();
});
}
Then use it like this:
Route::get('/profile/{user}', function (User $user) {
return $user->email;
});


