Route Model Binding

#Implicit binding

With closure

use App\Models\User;
Route::get('/users/{user}', function (User $user) {
    return $user->email;
});
// /user/1 --> User::where('id', '=', 1);

With controller action

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]);
}

With custom resolution column

use App\Models\Post;
Route::get('/posts/{post:slug}', function (Post $post) {
    return $post;
});
// /posts/my-post --> Post::where('slug', '=', 'my-post');

Always use a different column to resolve

// in App\Models\Post
public function getRouteKeyName()
{
    return 'slug';
}

Multiple models - second is child of first

use App\Models\Post;
use App\Models\User;
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
});

Convenient way to automatically inject the model instances directly into your routes

Comments