Laravel 4 : How to pass multiple optional parameters

不打扰是莪最后的温柔 提交于 2019-11-29 00:02:23
Razor

If you have multiple optional parameters

Route::get('test',array('as'=>'test','uses'=>'HomeController@index'));

And inside your Controller

 class HomeController extends BaseController {
    public function index()
    {
       // for example public/test/id=1&page=2&opt=1
       if(Input::has('id'))
           echo Input::get('id'); // print 1
       if(Input::has('page'))
           echo Input::get('page'); // print 2
       //...
    }
 }

Named parameters are usually done as route segments but without explicit naming. So for example you could o something like this:

Route:get('test/{id?}/{page?}/{opt?}', function ($id = null, $page = null, $opt = null) {
    // do something
});

$id, $page and $opt are all optional here as defined by the ? in the segment definitions, and the fact that they have default values in the function. However, you'll notice there's something of a problem here:

  1. They have to appear in the URL in the correct order
  2. Only $opt is truly optional, $page must be supplied if $opt is, and $id must be if $page is

This is a limitation brought about by the way that Laravel maps the named segments to function/method parameters. You could theoretically implement your own logic to make this work, however:

Route:get('test/{first?}/{second?}/{third?}', function ($first = null, $second = null, $third = null) {
    if ($first) {
        list($name, $value) = @explode('=', $first, 2);
        $$name = $value;
    }
    if ($second) {
        list($name, $value) = @explode('=', $second, 2);
        $$name = $value;
    }
    if ($third) {
        list($name, $value) = @explode('=', $third, 2);
        $$name = $value;
    }

    // you should now have $id, $page and $opt defined if they were specified in the segments
});

Not that this is a very naïve solution, relying on blind exploding by = as well as setting the name of an arbitrarily-inputted variable (which is obviously asking for trouble). You should add more checking to this code, but it should give you an idea of how to get over the aforementioned two problems.

It should probably be noted that this is kinda going against the 'right way' to do routing and URIs in Laravel, so unless you really need this functionality, you should rethink the way you are forming these URIs to a way that the Laravel framework is more set-up for.

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