php

Explaining Route Model Binding

One of the most common routing patterns is that the first line of any controller method tries to find the resource with the given ID.

Route::get('stores/{id}', function($id) {
    $stores = Store::find($id);
});

Laravel provides a feature that simplifies this pattern called “route model binding.” This allows you to define that a particular parameter name (e.g., ({stores}) will indicate to the route resolver that it should look up an Eloquent record with that ID and then pass it in as the parameter instead of just passing the ID.

There are two kinds of route model binding: implicit and custom (or explicit).

Implicit Route Model Binding

The simplest way to use route model binding is to name your route parameter something unique to that model (e.g., name it $store instead of $id), then typehint that parameter in the closure/controller method and use the same variable name there. It’s easier to show than to describe, so take a look at the next example:

Explicit route model binding

Route::get('stores/{store}', function(Store $store){
    return view('stores.show')->with('store', $store);
});

Because the route parameter ({store}) is the same as the method parameter ($store), and the method parameter is type hinted with a Conference model (Store $store), Laravel sees this as a route model binding. Every time this route is visited, the application will assume that whatever is passed into the URL in place of {store} is an ID that should be used to look up a Store and then that resulting model instance will be passed into your closure or controller method.

Custom Route Model Binding

To manually configure route model binding, add a line like the one in the following example to the boot() method in App\Providers\RouteServiceProvider.

public function boot(Route $router)
{
   // Just allows the parent's boot() method to still run
   parent::boot($router);
   // Perform the binding
   $router->model('shop', Store::class);
}

You’ve now defined that whenever a route has a parameter in its definition named {shop}, the route resolver will return an instance of the Store class with the ID of that URL parameter.

About the author

laravelrecipies