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

laravel route variables passing null values give url error

我有一条路线 有 3 个可选的 变量在 Controller

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

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

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

当变量的值为 null 时,url 中不会显示

http://localhost:8000/gegonota///1

并给我路由错误,比如它没有找到特定的 url。

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

您可能有兴趣使用 Optional Path Parameter,如 Laravel 文档中所述。这意味着您将拥有:

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

希望这能解决问题。

更新

尽管我不能说这是解决方法,因为您说重新排列变量并没有解决问题。我宁愿将这些可选变量作为请求参数传递以简化操作,即我的 url 看起来像:

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

因此,我已经可以将每个预期参数的默认值设置为 null,而不是处理由于在我的 url 中使用这种奇怪的 /// 可能引起的不一致:

//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'

])

除非有异常需要将那些可选变量传递给路径,否则将其作为请求参数显然更容易和更好。 希望这会更好。