Home » Php » php – Laravel 4 : How to pass multiple optional parameters

php – Laravel 4 : How to pass multiple optional parameters

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am new to laravel and I am really struggling to understand how to pass multiple optional url parameters.

What is the standard way to code routes when passing 3 optional parameters to the controller?

Also is there a way to code a route to allow named parameters to be passed to the controller?

such as

public/test/id=1&page=2&opt=1
or 
public/test/id=1/page=2/opt=1

Thanks for any help

How to&Answers:

If you have multiple optional parameters

Route::get('test',array('as'=>'test','uses'=>'[email protected]'));

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
       //...
    }
 }

Answer:

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.