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
Named parameters are usually done as route segments but without explicit naming. So for example you could o something like this:
$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:$opt
is truly optional,$page
must be supplied if$opt
is, and$id
must be if$page
isThis 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:
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.
If you have multiple optional parameters
And inside your Controller