Laravel 4: How to pass a few optional parameters

I'm new to laravel, and I'm really trying to figure out how to pass a few optional url parameters.

What is the standard way to encode routes when passing 3 extra parameters to the controller?

Is there also a way to encode a route that allows you to pass named parameters 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

+6
source share
2 answers

If you have a few 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 //... } } 
+7
source

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

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

$id , $page and $opt all optional here, as defined ? in segment definitions, and the fact that they have default values ​​in the function. However, you will notice something like a problem here:

  • They should appear in the url in the correct order
  • Only $opt really optional, $page should be specified if $opt is, and $id should be if $page is

This limitation is due to the fact that Laravel maps named segments to function / method parameters. Theoretically, you could implement your own logic to do this work:

 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 it was a very naive decision, relying on blind blasting on = , as well as on setting the name of an arbitrarily entered variable (which, obviously, requires trouble). You should add additional verification to this code, but it should give you an idea of ​​how to overcome the above two problems.

It should probably be noted that this seems like the β€œright way” to perform routing and URIs in Laravel, so if you really don't need this functionality, you should rethink how you configure these URIs so that the Laravel Frame is more configured for.

+6
source

All Articles