Laravel 5.3 Route model binding with multiple parameters

一曲冷凌霜 提交于 2019-12-10 16:39:31

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39289608/laravel-5-3-route-model-binding-with-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!