【问题标题】:Laravel route/{variable?} not working when not enteredLaravel route/{variable?} 未输入时不起作用
【发布时间】:2017-12-04 18:08:52
【问题描述】:

所以在我的 web.php 中我有这样的路线:

Route::get('city/{city_id?}', function($city_id) {
    return view('search');
});

但是当我尝试只输入 'localhost/public/city/' 时,它会显示一个错误:

"Type error: Too few arguments to function Illuminate\Routing\Router::{closure}(), 0 passed in /opt/lampp/htdocs/laravelcourse/vendor/laravel/framework/src/Illuminate/Routing/Route.php on line 198 and exactly 1 expected "

当我输入变量时,它工作得很好。 ? 符号不应该意味着我可以输入它或将其留空并且它仍然应该工作吗?

【问题讨论】:

  • 在这个例子中 $city_id 没有在任何地方使用。只要确保你知道如果你想在那里使用它,你需要将 $city_id 传递给视图。
  • 你在哪里使用$city_id

标签: php laravel


【解决方案1】:

这应该可以,如果没有传递参数,您需要提供默认值。

Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});

【讨论】:

  • 是的,它奏效了。我以前试过,但没有,好像我错过了其他东西。感谢您的回答!
【解决方案2】:

应该是这样的:

Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});

请在此处阅读文档:Laravel optional routing

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2017-04-11
    • 2018-02-17
    • 2020-03-16
    相关资源
    最近更新 更多