In this tutorial, I will explain laravel 9 route model binding. In this example you will learn what is laravel route model binding and why we need route model binding and when we need route model binding in laravel.
You know that Laravel automatically injects ID to retrieve data from the eloquent model. But assume we need to fetch data without injecting the ID. How can we do that? In this scenario, we can use Laravel route model binding.
Let's see an example, instead of injecting a user's ID, we can inject the entire User
model instance that matches the given ID.
<?php
use App\Models\User;
use Illuminate\Support\Facades\Route;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
Now if you visit the URL /user/1 then it will return user data whose ID is 1. Of course, this laravel route model binding is also possible when using controller methods.
<?php
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
// Controller method definition...
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}
Customizing The Route Model Binding Key
Now assume we would like to change the key name like we want to fetch data according to slug
instead of ID
. To do so, we can specify the column in the route parameter definition:
<?php
use App\Models\Post;
Route::get('/posts/{post:slug}', function (Post $post) {
return $post;
});
Hope it can help you.