Laravel 4 Optional Route Parameter

前端 未结 2 698
灰色年华
灰色年华 2021-01-06 01:47

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         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 02:22

    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) {...}
    

提交回复
热议问题