代码之家  ›  专栏  ›  技术社区  ›  Oto Shavadze

具有多个可选参数的URL

  •  0
  • Oto Shavadze  · 技术社区  · 7 年前

    brand , year color

    简化路线示例:

    Route::get('/cars/{brand?}/{year?}/{color?}', function ($brand = NULL, $year = NULL, $color = NULL) {
    
        echo "brand is:".$brand."<br>";
        echo "year is:".$year."<br>";
        echo "color is:".$color."<br>";
    
    });
    

    我不知道如何通过考试,只是举个例子 年 参数?

    如果传递了所有3个参数,则有效,例如: /cars/_/2010/_ 但这是非常不雅观的解决方案。

    什么是正确的方法?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Bruno Francisco    7 年前

    我不知道这是否可能,因为你可能最终只传递了2个参数,而Laravel无法理解这是否可能 brand color 或 year .

    public function getCars(Request $request){
            Validator::validate($request->all(), [
                'brand' => 'nullable|string',
                'year' => 'nullable|integer',
                'color' => 'nullable|string'
            ]);
    
            $cars = Car::select('id', '...');
    
            if($request->has('brand')){
                // get cars with that brand
                $cars->where('brand', $request->brand);
            }
    
            // ... and so on with the other parameters
    
            $cars = $cars->paginate(10); // or $cars->get()
    
        }
    

    这是一个相当简单的示例,因此您必须根据自己的需要进行自定义。希望有帮助。

        2
  •  0
  •   andcl    7 年前

    正如官方文件所说, . 在这个特定的例子中,Laravel必须知道每个参数是哪一个的唯一方法就像你建议的那样(参见 https://laravel.com/docs/5.6/routing#route-parameters ).

    得到 ,并将它们作为请求后数据而不是在查询字符串本身中传递。