Laravel route / {variable?}未输入时无效

时间:2017-12-04 18:08:53

标签: php laravel

所以在我的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 "

当我输入变量时,它可以正常工作。不应该?符号表示我可以输入它或者可以将其留空并仍然可以工作吗?

2 个答案:

答案 0 :(得分:8)

这应该有效,如果没有传递参数,你需要提供一个默认值。

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

答案 1 :(得分:2)

应该是这样的:

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

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