Search code examples
laravel-routinglaravel-5.3

Laravel 5.3 Route model binding with multiple parameters


Is it possible to have route model binding using multiple parameters? For example

Web Routes:

Route::get('{color}/{slug}','Products@page');

So url www.mysite.com/blue/shoe will be binded to shoe Model, which has color blue.


Solution

  • First of all, it would feel more natural to have a route like the following:

    Route::get('{product}/{color}', 'Products@page');
    

    and to resolve product by route binding, and just use the color parameter in the controller method directly, to fetch a list of blue shoes for example.

    But let's assume that for some reason it's a requirement. I'd make your route a bit more explicit, to start with:

    Route::get('{color}/{product}', 'Products@page');
    

    Then, in the boot method of RouteServiceProvider.php, I would add something like this:

    Route::bind('product', function ($slug, $route) {
        $color = $route->parameter('color');
    
        return Product::where([
            'slug'  => $slug,
            'color' => $color,
        ])->first() ?? abort(404);
    });
    

    first here is important, because when resolving route models like that you effectively want to return a single model.

    That's why I think it doesn't make much sense, since what you want is probably a list of products of a specific color, not just a single one.

    Anyways, I ended up on this question while looking for a way to achieve what I demonstrated above, so hopefully it will help someone else.