Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel route/{variable?} not working when not entered

Tags:

php

laravel

So in my web.php I have route like this:

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

But when I try to enter just 'localhost/public/city/' it displays me an error:

"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 "

When I enter the variable it works just fine. Shouldn't ? symbol mean that I may enter it or may leave it blank and it still should work?

like image 872
PhpNewbie Avatar asked Dec 04 '17 18:12

PhpNewbie


2 Answers

This should work, you need to provide a default value in case if no parameter is passed.

Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});
like image 151
Sapnesh Naik Avatar answered Nov 12 '22 10:11

Sapnesh Naik


Should be like this:

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

Please read documentation here: Laravel optional routing

like image 2
Javid Karimov Avatar answered Nov 12 '22 11:11

Javid Karimov