Laravel 4 Route issues with multiple and optional get params

China☆狼群 提交于 2020-01-14 03:35:34

问题


I am creating a webservice with Laravel 4 and I am facing an issue with Optional params. Consider scenario below::

http://webservices.example.com/city/mumbai/q/hospital/

Which renders results for a search page with few filters e.g. category and location and ofcourse params for pagination too. Now these Filter params may be optional and may not have a pre-defined order coz it depends on how user might select filters. So lets say following URL forms are possible

http://webservices.example.com/city/mumbai/q/north/locality/myarea http://webservices.example.com/city/mumbai/q/north/locality/myarea/category/eye-hospital

http://webservices.example.com/city/mumbai/q/north/category/eye-hospital/locality/my-area

The error I had was single URL form definition in app/routes.php didn't helped.

Route::get('/city/{city}/q/{q}/locality/{locality}/category/{category}',
        array('before' => 'check_city|check_query', 'uses' => 'SearchController@searchData'));

after referring stackoverflow I saw this link Laravel 4 optional parameter After I have created multiple route definition for different permutations and combination, Which is working fine. But If my get params are more then, its not really possible for us to define all permutations. So I am looking for a better way.

Any help is much appreciated!!


回答1:


I didn't test this code at all, but you could try something like this:

Route::get('{:params}', array('uses' => 'SearchController@searchData))->where('params', '.+');

Then in your SearchController@searchData:

 public function searchData($search = null)
 {
      $params = $this->extractSearchParams($search);

      // do other stuff here with params
 }

 protected function extractSearchParams($search)
 {
      $parts = explode($search, '/');

      $params = array();

      foreach ($i = 0; $i < count($params); $i += 2)
      {
            $params[$parts[$i]] = $parts[$i + 1];
      }

      return $params;
 }


来源:https://stackoverflow.com/questions/22140898/laravel-4-route-issues-with-multiple-and-optional-get-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!