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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16846397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:50:14  来源:igfitidea点击:

Missing argument for closure with optional parameter

parametersclosureslaravellaravel-4optional

提问by Triccum

I am in the process of working my way through a couple tutorials for Laravel 4 and I have run into a snag that I cannot figure out or comprehend as to why it is running incorrectly.

我正在学习 Laravel 4 的几个教程,但遇到了一个问题,我无法弄清楚或理解它为什么运行不正确。

What I am trying to do compose a route that looks at the URL, and then works logically based on that. Here is my current code:

我正在尝试编写一个查看 URL 的路由,然后基于该 URL 进行逻辑工作。这是我当前的代码:

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

So if the URL is http://localhost/books, the page should return "Books index." If the URL reads http://localhost/books/mysterythe page should return "Books in the mystery category."

因此,如果 URL 是http://localhost/books,则页面应返回“图书索引”。如果 URL 读取http://localhost/books/mystery页面应返回“神秘类别的书籍”。

However I am getting a 'Missing argument 1 for {closure}()' error. I have even referred to the Laravel documentation and they have their parameters formated exactly the same way. Any help would be appreciated.

但是,我收到“{closure}() 缺少参数 1”错误。我什至参考了 Laravel 文档,它们的参数格式完全相同。任何帮助,将不胜感激。

回答by Fernando Montoya

If the genre is optional, you have to define a default value:

如果流派是可选的,则必须定义一个默认值:

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

回答by user3467678

Genre is optional, you must define a default value to $genre. $genre=nullso that it matches for "Book index"of your code.

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

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


return "Books in the {$genre} category";
});