Normally it is very simple to add parameters using the Laravel url
helper method -- as simple as:
url("foo/show/", [333]); // site.com/foo/show/333
However, how do you do it when parameters are at a midpoint, such as:
url("foo/?/bar/?/show", [333,444]);
I have tried the following which all fail (some come close though):
url("foo/?/bar/?/show", [333,444]);
// site.com/foo//333/444?/bar/?/show
url("foo/{a}/bar/{b}/show", [333,444]);
// site.com/foo/{a}/bar/{b}/show/333/444
url("foo/{a}/bar/{b}/show", ['a' => 333, 'b' => 444]);
// site.com/foo/{a}/bar/{b}/show/333/444
The ?
is obviously important, because it gets close to the result...
I am specifically talking about unnamed routes. So the route
function is not in question. Named routes aren't possible in the current project, so I need to reiterate I am looking for the use of the url
method.
I 100% agree that normally named routes are the way to go.
Try this:
url(sprintf("foo/%d/bar/%d/show", 333, 444));
If you name your routes, you can use the route
function.
Route::get('some/{test}/{a}/testing', ['as' => 'testRoute', 'uses' => 'SomeController@someMethod']);
Route::get('test', function() {
echo route('testRoute', ['test' => 'green', 'a' => 'purple']);
});
This would output http://yourapp.local/some/green/purple/testing
I prefer this approach rather than hardcoding url on different pages.
Route::get('foo/{param1}/bar/{param2}/show', array('as' => 'someRoute', 'uses' => 'SomeController@someMethod'))
->where(array(
'param1' => '[a-zA-Z0-9-]+',
'param2' => '[a-zA-Z0-9-]+'
));
Controller:
public function someMethod($param1, $param2)
{
return $param1 . $param2;
}
// Assuming you passed params in controller
{{ route('someRoute') }}
// If not
{{ route('someRoute', ['param1' => 'test', 'param2' => 'routing']) }}
If parameters are not GET
request parameters, but parts of the path at a midpoint (like exactly asked in a question), it is possible to generate url using Laravel's url()
helper without using sprintf()
at all:
url('foo', [333, 'bar', 444, 'show']);
// site.com/foo/333/bar/444/show
However, as pointed in other answers – named routes are preferable.