laravel 中可选参数的路由绑定

route binding for optional parameters in laravel

我有这样的路线:

$this->get('/{citySlug}/{catSlug1?}/{catSlug2?}/{sightSlug?}', function () {
  return 'Hello World';
});

如何绑定在RouteServiceProvider.php中的boot()函数中查看?

我试试这个:

Route::bind('citySlug', function ($citySlug, $route) { ... });

   Route::bind('catSlug1', function ($citySlug, $route) { ... });

   Route::bind('catSlug2', function ($catSlug2, $route) { ... });

   Route::bind('catSlug3', function ($catSlug3, $route) { ... });

   Route::bind('sightSlug', function ($sightSlug, $route) { ... });

但是可选参数是错误的...上面有什么问题?

更新:

example.com/city_slug/cat1/cat2  It works.

example.com/city_slug/cat1/cat2/sight_slug It works.

example.com/city_slug/cat1/sight_slug It not works!

肯定不行。尝试了解您正在使用的路线:-

$this->get('/{citySlug}/{catSlug1?}/{catSlug2?}/{sightSlug?}', function () {
    return 'Hello World';
});
citySlug i.e. mandatory according to your route
catSlug1,catSlug2,sightSlug i.e this is not manadtory because you added question mark as per laravel documentation

现在您正在尝试访问这个 url :-

example.com/city_slug/cat1/sight_slug --- Definitely it will not work because
                                          your **sight_slug** is treat like **catSlug2** 
                                          that's why its not working 

解决方法:-

For this you can use $_GET parameters and create one route something like that:-
$this->get('/filter-query', function () {
   return 'Hello World';
});

现在您的 url 将如下所示:-

example.com/filter-query?citySlug=cityname&cat1=catvalue&cat2=&sightSlug=sightslugvalue

之后在函数中你可以回显$_GET,你的问题就解决了。 希望对您有所帮助!