Reputation: 143
I have a route that has 3 optional variables declared as null in Controller
Route::get('gegonota/{gid?}/{cid?}/{nid?}', [
'uses' => 'GegonosController@index',
'as' => 'gegonota'
]);
and even i change the order of the parameter the problem still exists.
public function index($gid = null, $cid = null, $nid = null)
When values of the variables are null are not showing in the url like
http://localhost:8000/gegonota///1
and gives me route errors like it didnt find the specific url.
I have to check and substitute null to 0 so that has something in the url and give no error. Which is laravel way to do that avoiding all the trouble. thanks
Upvotes: 2
Views: 9120
Reputation: 7334
You may be interested in using Optional Path Parameter as stated in Laravel doc. This means you'll have:
Route::get('gegonota/{gid}/{cid}/{nid?}', [
'uses' => 'GegonosController@index',
'as' => 'gegonota'
]);
Hope this solves the issue.
Update
Even though I cannot say this is the fix since you said rearranging the variable did not solve the issue. I would rather pass those optional variables as request parameters to make things easy, i.e my url would look like:
http://localhost:8000/gegonota/?gid=&cid=&nid=
Therefore, I can already set the default for each of the expected parameters as null rather than deal with inconsistency that may arise from having this kind of wierd ///
in my url:
//In a controller
public funtion index()
{
//put them in an array
$my_variables = request()->only(['gid', 'cid', 'nid']);
//or this way
$gid = request()->get('gid');
$cid = request()->get('cid');
$nid = request()->get('nid');
//they are default to null if not existing or have no value
}
This means your route declaration is simple, i.e:
Route::get('gegonota', [
'uses' => 'GegonosController@index',
'as' => 'gegonota'
])
Unless there is an exceptional need to pass those optional variable to the path, its clearly easier and better to have it as request parameters. Hope this is better.
Upvotes: 1