Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Optional Route Parameter

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.

like image 627
davidcoder Avatar asked Sep 17 '13 09:09

davidcoder


1 Answers

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) {...}
like image 52
Sergiu Paraschiv Avatar answered Sep 20 '22 19:09

Sergiu Paraschiv