Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing argument for closure with optional parameter

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.

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:

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/mystery the page should return "Books in the mystery category."

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.

like image 479
Triccum Avatar asked May 30 '13 21:05

Triccum


2 Answers

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.";  
});
like image 117
Fernando Montoya Avatar answered Nov 18 '22 12:11

Fernando Montoya


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

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


return "Books in the {$genre} category";
});
like image 1
user3467678 Avatar answered Nov 18 '22 13:11

user3467678