laravel 如何在laravel路由中定义两个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45291695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to define two parameter in laravel route
提问by K1-Aria
im using laravel 5.4 and i have a brands and a products table. i want to define two parameter in route and get them in controller or RouteServiceProvider to search.
我使用 Laravel 5.4,我有一个品牌和一个产品表。我想在路由中定义两个参数并将它们放入控制器或 RouteServiceProvider 中进行搜索。
imagine : site.com/samsung/ => get all products with samsung brand.
想象一下:site.com/samsung/ => 获取所有带有三星品牌的产品。
and : site.com/samsung/galaxys8 => get all products with samsung brand and galaxys8 model
和:site.com/samsung/galaxys8 => 获取所有带有三星品牌和 Galaxys8 型号的产品
i can define this using two separate route and controller method : (define route one with 1 parameter{brand} and controller@method1 and define route two with 2 parameters {brand}/{product} and controller@method2)
我可以使用两个单独的路由和控制器方法来定义它:(用 1 个参数{brand} 和 controller@method1 定义路由一,并用 2 个参数 {brand}/{product} 和 controller@method2 定义路由二)
can i do this better? im a little new in laravel . thank you
我可以做得更好吗?我对 Laravel 有点陌生。谢谢你
Route::get('/{brand}', 'AdvertismentController@show');
Route::get('/{brand}/{product}', 'AdvertismentController@show2');
public function show($brand)
{
$brands = Advertisment::where('brand' , $brand)->get();
return $brands;
}
public function show2($brand , $product)
{
$products = Advertisment::where('product' , $product)->get();
return $products;
}
回答by Cong Chen
I guess that you want to combine the similar controller actions, you can use optional parameters like this:
我猜你想结合类似的控制器动作,你可以使用这样的可选参数:
Route::get('/{brand}/{product?}', 'AdvertismentController@show');
public function show($brand, $product = null)
{
if (!is_null($product)) {
$results = Advertisment::where('product' , $product)->get();
} else {
$results = Advertisment::where('brand' , $brand)->get();
}
return $results;
}