I would like to know how to add an optional route parameter for a controller method:
Currently I have a route, shown below:
Route::get('devices/{code}/{area}','HomeController@getDevices');
and a controller method:
public function getDevices($code=NULL,$area) {...}
My get request will look like:
/devices/A/ABC
It's working fine, but I want the {code} parameter to be optional so that I can get data in different ways:
/devices//ABC or
/devices/ABC
I've tried the following, but all failed with NotFoundHttpException
Route::get('devices/{code?}/{area}','HomeController@getDevices');
Route::get('devices/(:any?)/{area}','HomeController@getDevices');
Thanks for your help.
The optional parameter needs to be at the end of the URL.
So yours is a clear Incorrect usage of default function arguments, as described here. This is the reason your code does not work as you expect it to.
You'll have to reverse the order of those two parameters or implement different methods for those cases, taking into account that you'll need some sort of prefix to differentiate between them:
Route::get('devices/area/{area}','HomeController@getDevicesByArea');
Route::get('devices/code-and-area/{code}/{area}','HomeController@getDevicesByAreaAndCode');
public function getDevicesByAreaAndCode($area, $code = NULL) {...}
public function getDevicesByArea($area) {
return $this->getDevicesByAreaAndCode($area);
}
OR, as I said before, reverse the parameters:
Route::get('devices/area-and-code/{area}/{code?}','HomeController@getDevicesByAreaAndCode');
public function getDevicesByAreaAndCode($area, $code = NULL) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With