【问题标题】:URL with multiple optional parameters带有多个可选参数的 URL
【发布时间】:2019-03-11 18:05:58
【问题描述】:

假设我有一个搜索汽车的页面,页面有 3 个可选参数,brandyearcolor

简化路线示例:

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>";

});

我不知道如何仅传递 year 参数?

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

什么是正确的方法?

【问题讨论】:

  • 您能举一些您想使用的 URL 示例吗?
  • @Jonathon - 我希望 Laravel 有类似“命名参数路由方式”的东西,例如 /cars/year:2010,但参数取决于顺序,所以我不知道如何构建 URL,当我只需要传递某些参数

标签: php laravel laravel-5.4


【解决方案1】:

我不知道这是否可行,因为您最终可能只传递了 2 个参数,而 Laravel 将无法理解这是 brandcolor 还是 year

关于我使用的 URL 参数方法,我将留下两分钱:

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】:

    正如官方文档所说,路由参数会根据它们的顺序注入到路由回调/控制器中。在这种特定情况下,Laravel 必须知道每个参数的唯一方法就像您建议的那样(请参阅https://laravel.com/docs/5.6/routing#route-parameters)。

    无论如何,如果执行搜索需要 3 个参数,您可能会考虑将请求动词从 GET 更改为 POST,并将所有参数作为 POST 传递请求数据而不是查询字符串本身。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 2016-11-15
      • 2013-06-09
      • 2020-08-14
      • 1970-01-01
      • 2020-01-30
      相关资源
      最近更新 更多