Optional parameter in the middle of a route

前端 未结 3 2035
感动是毒
感动是毒 2020-12-03 21:42

Is there any way to add an optional parameter in the middle of a route ?

Example routes:

/things/entities/
/things/1/entities/

I t

3条回答
  •  借酒劲吻你
    2020-12-03 21:58

    The "correct" answer for this question is; No, you can't and shouldn't use an optional parameter unless it's at the end of the route/url.

    But, if you absolutely need to have an optional parameter in the middle of a route, there is a way to achieve that. It's not a solution I would recommend, but here you go:

    routes/web.php:

    // Notice the missing slash
    Route::get('/test/{id?}entities', 'Pages\TestController@first')
        ->where('id', '([0-9/]+)?')
        ->name('first');
    
    Route::get('/test/entities', 'Pages\TestController@second')
        ->name('second');
    

    app/Http/Controllers/Pages/TestController.php:

    resources/views/test.blade.php:

    
    
    
        First route
    
    
    
    
        Second route
    
    

    Both links will trigger the first-method in TestController. The second-method will never be triggered.

    This solution works in Laravel 6.3, not sure about other versions. And once again, this solution is not good practice.

提交回复
热议问题