缺少带有可选参数的闭包参数

时间:2013-05-30 21:45:48

标签: parameters closures laravel laravel-4 optional

我正在为Laravel 4完成一些教程,我遇到了一个我无法理解或理解为什么它运行不正确的障碍。

我想要做的是组成一个查看URL的路由,然后根据它进行逻辑工作。这是我目前的代码:

Route::get('/books/{genre?}', function($genre)  
{  
    if ($genre == null) return 'Books index.';  
    return "Books in the {$genre} category.";  
});

因此,如果网址为http://localhost/books,则该网页应返回“图书索引”。如果网址显示http://localhost/books/mystery,则网页应返回“神秘类别中的图书”。

但是我收到了'miss}()错误的'缺少参数1'。我甚至提到了Laravel文档,他们的参数形式完全相同。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:9)

如果类型是可选的,则必须定义默认值:

Route::get('/books/{genre?}', function($genre = "Scifi")  
{  
    if ($genre == null) return 'Books index.';  
    return "Books in the {$genre} category.";  
});

答案 1 :(得分:1)

类型是可选的,您必须将默认值定义为$genre$genre=null,以便与您的代码的“图书索引”相匹配。

Route::get('books/{genre?}', function($genre=null)
{
    if (is_null($genre)) 
        return "Books index";


return "Books in the {$genre} category";
});
相关问题