Model binding — Laravel 10 Discovery Training

In this tutorial, we will learn how to use the binding model in Laravel which allows us to pre-fetch entities from the database in the actions of our routes. This is an interesting concept that can save you time.

The binding model allows us to bind a route parameter to a database model. For example, suppose we have a route that takes an ID and a slug as parameters.

function show (string $slug, string $id) {
    // On récupère l'article à partir de son ID
    $post = Post::findOrFail($id);
    // ...
}

This logic will very often be present in the code of our controllers and Laravel can do this dynamically by linking by automatically retrieving the data from the primary key.

To use the binding model, you must first change the naming of your route parameters. In our example, we’ll change the ID to post.

Route::get('/blog/{slug}-{post}', [PostController::class, 'show'])

Then you need to rename the parameter $post in your controller by giving it a type corresponding to the model you want to use.

function show (string $slug, Post $post) {
    // $post sera automatiquement récupéré par Laravel
    // ...
}

If you try to access an article that does not exist, Laravel will throw an exception which will result in a 404 error.

You can also choose the field to use when resolving this model binding in case you don’t want to use the primary key.

Route::get('/blog/{post:slug}', [PostController::class, 'show'])