ZKelo's avatar
Level 1

route() helper returns invalid URL for named route with two optional params

I have two routes. First is main route for home page (url: /), second is for test and have two optional params - id and name. I want to make redirect from home page to named route "test", but route() helper returns invalid URL

This is my code:

/**
 * @var Laravel\Lumen\Routing\Router $router
 */

$router->get('/', function () {
    return route('test');
    // return redirect()->route('test');
});

$router->get('/test[/{id}[/{name}]]', [
    'as' => 'test', function ($id = 0, $name = '') {
        if ($name) {
            return "Name: $name (ID: $id)";
        }
        if ($id) {
            return "ID: $id";
        }
        return 'Need an id or name!';
    }
]);

This is what returns route() helper for route test: https://example.com/test[/{id}[/{name}]]

What I'm doing wrong?

0 likes
12 replies
Omda's avatar

@zkelo user this

Route::get('/', function(){
    return redirect()->route('test');
});
Omda's avatar

@zkelo if that not working for you trying this will solve your problem


$router->get('/', function () {
    return redirect()->route('test', [1, 'Zkelo']);
});

$router->get('/test/{id}/{name}', [
    'as' => 'test', function ($id = 0, $name = '') {
        if ($name) {
            return "Name: $name (ID: $id)";
        }
        if ($id) {
            return "ID: $id";
        }
        return 'Need an id or name!';
    }
]);

ZKelo's avatar
Level 1

@omda I need to redirect user to this page (test) without any default params

ZKelo's avatar
Level 1

@omda and I just don't know why route() returns invalid URL with brackets like in route declaration. I think in my case URL that returned by route() must be like this example.com/test

ftiersch's avatar

Are you sure Lumen supports nested optional parameters?

ZKelo's avatar
Level 1

I don't know. How I can check that?

Omda's avatar

@zkelo okay so you can try this replase this $router->get('/test/{id}/{name}' by this

$router->get('/test/{id?}/{name?}'
ftiersch's avatar

That's Laravel syntax. He's using Lumen.

@zkelo Try with just one parameter and see if that works as expected

1 like
ftiersch's avatar

Yes, but I don't think nested parameters are possible.

Maybe this works:

'/test[/{id}][/{name}]'
ZKelo's avatar
Level 1

This isn't works. Returns example.com/test[/{id}]

Please or to participate in this conversation.