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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:22:31  来源:igfitidea点击:

how to define two parameter in laravel route

phplaravellaravel-5routeslaravel-5.3

提问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;
}

回答by Igor Phelype Guimar?es

Just like on this example question here

就像这里的示例问题一样

You pass two arguments on the URI:

您在 URI 上传递两个参数:

Route::get('/{brand}/{product}', 'AdvertismentController@show2');

And on the view:

并在观点上:

route('remindHelper',['brand'=>$brandName, 'product'=>productId]);