【问题标题】:route binding for optional parameters in laravellaravel 中可选参数的路由绑定
【发布时间】:2023-04-01 07:20:01
【问题描述】:

我有这样的路线:

$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!

【问题讨论】:

  • 你有什么错误?我看到你昨天也问了这个问题。但是,绑定看起来正确,可选参数看起来也正确。
  • 我可以解决的比昨天更多。请检查我的更新。我的问题是动态类别和子类别....我知道对于 laravel 工作人员来说一定很简单...但是我在互联网上找不到任何文档或帮助...
  • 对于可选参数,您不能这样做。您最后一个示例中的sight_slug 将被视为catSlug2

标签: php laravel laravel-routing


【解决方案1】:

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

$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 并且你的问题将得到解决。 希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2018-01-08
    • 2017-09-30
    相关资源
    最近更新 更多