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/{cod
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) {...}
You can do this with Laravel 4 if you want, and it may be convenient for some JSON calls where a parameter not on the end of the URI may need to be empty.
The key is setting up a route specifically for the empty parameter. This route:
Route::get('devices//{area}','HomeController@getDevicesByArea');
will catch the URI "devices//myarea" and send it to:
public function getDevicesByArea($area) {...}
Where the code is supplied, the main route can catch that:
Route::get('devices/{code}/{area?}','HomeController@getDevicesByCode');
sending the code and optional area to:
public function getDevicesByArea($code, $area = '') {...}
This is not to say that swapping the parameters around in this example is not the better solution especially if the URL is going to be handled by a human. But I'm just adding for the record here that what was originally requested is possible, and can make some AJAX requests easier to deal with.