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

现在您正在尝试访问此网址:-

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';
});

现在您的网址将如下所示:-

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

之后在函数中您可以回显 $_GET 并且您的问题将得到解决。希望能帮助到你!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章