Laravel 4 Optional Route Parameter

我怕爱的太早我们不能终老 提交于 2019-11-30 17:08:20

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18846688/laravel-4-optional-route-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!