laravel路由变量传递空值给出url错误

时间:2017-07-23 21:49:02

标签: php laravel routes optional-variables

我有一条在Controller

中声明为null的3个可选变量的路由
Route::get('gegonota/{gid?}/{cid?}/{nid?}', [
'uses' => 'GegonosController@index', 
'as' => 'gegonota'
]);

即使我更改了问题仍然存在的参数顺序。

public function index($gid = null, $cid = null, $nid = null)

如果变量的值为null,则不会显示在

等网址中
http://localhost:8000/gegonota///1

并给我路线错误,就像没找到特定的网址一样。

我必须检查并将null替换为0,以便在url中包含某些内容并且不会出错。 这是避免所有麻烦的laravel方法。 感谢

1 个答案:

答案 0 :(得分:1)

您可能有兴趣使用Laravel doc中所述的Optional Path Parameter。这意味着您将拥有:

Route::get('gegonota/{gid}/{cid}/{nid?}', [
    'uses' => 'GegonosController@index', 
    'as' => 'gegonota'
]);

希望这可以解决问题。

<强>更新

即使我不能说这是修复,因为你说重新安排变量并没有解决问题。我宁愿将这些可选变量作为请求参数传递,以使事情变得简单,即我的URL看起来像:

http://localhost:8000/gegonota/?gid=&cid=&nid=

因此,我已经可以将每个预期参数的默认值设置为null,而不是处理因我的网址中出现这种奇怪的///而导致的不一致:

//In a controller
public funtion index()
{
    //put them in an array
    $my_variables = request()->only(['gid', 'cid', 'nid']);

    //or this way
    $gid = request()->get('gid');
    $cid = request()->get('cid');
    $nid = request()->get('nid');

   //they are default to null if not existing or have no value
}

这意味着您的路线声明很简单,即:

Route::get('gegonota', [
    'uses' => 'GegonosController@index', 
    'as' => 'gegonota'

])

除非例外需要将这些可选变量传递给路径,否则将其作为请求参数显然更容易也更好。 希望这更好。

相关问题