The following is the route
Route::get('{value1}/{optvalue1?}/{optvalue2?}/{value2}/{value3}/',
[
'uses' => 'Controller@control',
'as' => 'path_route'
]
);
My controller is setup as follows
function redirectSearchRequest(){
return redirect()->route('path_route', [
$value1,
isset($optvalue1) ? $optvalue1 : '',
isset($optvalue2) ? $optvalue2 : '',
$value2,
$value3
]);
}
public function control($value1, $iptvalue1 = null, $optvalue2 = null, $value2, $value3)
{
//process accordingly
}
Now the problem with this is if I had a url
which look like http://example.com/value1/optvalue1/optvalue2/value2/value3
. It works without any errors but the url can be sometimes without optvlaue1
and optvalue2
and the route returns http://example.com/value1////value2/value3
as expected laravel throws NotFoundHttpException
.
Further more to this problem Option
variable are not always present but when they are they should be exactly like how the route is set. I cannot change the order around :(.
Hopefully I am clear enough. Cheers for you help.
Optional variables work better when they're at the end, to avoid 404 errors like you are seeing. There are several workaround you can try:
Option 1:
Account for every possible variation of the route:
Route::get('{value1}/{optvalue1?}/{optvalue2?}/{value2}/{value3}/', Controller@control );
Route::get('{value1}/{optvalue1?}/{value2}/{value3}/', Controller@control );
Route::get('{value1}/{optvalue2?}/{value2}/{value3}/', Controller@control );
Route::get('{value1}/{value2}/{value3}/', Controller@control );
Option 2:
Use the optional parameters in query string
Route::get('{value1}/{value2}/{value3}/', Controller@control );
And just add ?optvalue1=something&optvalue2=something-else
Otherwise, it gets very complicated in identifying which parameter is which.
Option 3:
Another solution could be to default the values of optvalue1
and optvalue2
to something. E.g.
http://example.com/value1/null/null/value2/value3