Fusion
Fusion

Reputation: 5472

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.

Upvotes: 6

Views: 7641

Answers (3)

Sinan Eldem
Sinan Eldem

Reputation: 5728

Do not forget to declare the parameter types:

Route::delete('safedetail/{safeId}/{slug}', [
    'as' => 'safedetail.delete',
    'uses' => 'SafeDetailController@destroy',
])->where([
    'safeId' => '[0-9]+',
    'slug' => '[a-z]+',
]);

Upvotes: 0

osteel
osteel

Reputation: 608

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.

Upvotes: 14

Robin
Robin

Reputation: 1587

Try changing your controller to this:

class Pages extends Controller{

    public function single($lang, App\Page $page){

        dd($page);

    }

}

You must add the Page Model.

Upvotes: -2

Related Questions