Laravel 发送带有可选参数的查询字符串

Laravel send query string with optional parameters

我的路线设置为

Route::any('/{brand?}/{type?}/{city?}', 'SearchController@index')->name('search');

我想从我的控制器发送查询字符串(Form GET params)

经过搜索,我得到了这个,但它不能正常工作

return redirect()->route('search', [$brand->name, $type->name, 'search_model_from' => $request->search_model_from, 'search_model_to' => $request->search_model_to]);

return 回来了

localhost:8000/toyota/avalon/2018?search_model_to=2019

我要return

localhost:8000/toyota/avalon/?search_model_from=2018&search_model_to=2019

总的来说,我想要实现的是 SEO 友好的搜索功能

也许您应该像这样尝试将城市指定为 null :

return redirect()->route('search', [
    'brand' => $brand->name, 'type' => $type->name, 
    'city' => '', 'search_model_from' => $request->search_model_from, 
    'search_model_to' => $request->search_model_to
]);

我不确定,但这可能会发生,因为您在路由中定义了 3 个可选参数,并且由于您只发送其中两个,因此可能需要下一个(在本例中为 'search_model_from') url.

的第三个参数

也许如果您在 Controller 中为可选参数强制转换并设置默认值,就不会遇到这样的麻烦,如下所示:

public function index(string $brand='', string $type='', string $city='' , $other_parameters)