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.
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.
首先,有这样一条路线会感觉更自然:
Route::get('{product}/{color}', 'Products@page');
product
并通过路由绑定来解决,直接使用color
控制器方法中的参数,例如获取蓝鞋列表。
但是让我们假设由于某种原因这是一个要求。我会让你的路线更明确一点,首先是:
Route::get('{color}/{product}', 'Products@page');
然后,在 的boot
方法中RouteServiceProvider.php
,我会添加如下内容:
Route::bind('product', function ($slug, $route) {
$color = $route->parameter('color');
return Product::where([
'slug' => $slug,
'color' => $color,
])->first() ?? abort(404);
});
first
这很重要,因为在解析这样的路由模型时,您实际上希望返回单个模型。
这就是为什么我认为它没有多大意义,因为您想要的可能是特定颜色的产品列表,而不仅仅是单个产品。
无论如何,我在寻找一种方法来实现我上面展示的内容时最终解决了这个问题,因此希望它对其他人有所帮助。
不要忘记声明参数类型:
Route::delete('safedetail/{safeId}/{slug}', [
'as' => 'safedetail.delete',
'uses' => 'SafeDetailController@destroy',
])->where([
'safeId' => '[0-9]+',
'slug' => '[a-z]+',
]);
尝试将您的控制器更改为:
class Pages extends Controller{
public function single($lang, App\Page $page){
dd($page);
}
}
您必须添加页面模型。