首页 > 解决方案 > 从 Route Web.php 的 /profile/{username} 关键字中删除 /profile/ 不起作用

问题描述

我有一条路线

Route::get('/{username}', 'ProfileController@profile')->name('profile.view');

如果我把它放在文件中间,那么之后的所有路由都不起作用。

如果我把它放在底部,那么一切正常。

另外,如果我添加像 Profile 这样的任何工作,它就可以工作。

Route::get('profile/{username}', 'ProfileController@profile')->name('profile.view');

如何解决这个问题?

标签: laravel

解决方案


当您使用通配符匹配所有内容时,这就是它应该工作的方式。所以要么你把它放在文件的底部,它就会被用作一个后备路由,这意味着它上面的任何东西都不应该匹配,那么它将回退到那个路由。或者您可以使用正则表达式将用户名与使其与其他路由不同的东西相匹配,例如:

Route::get('{username}', 'ProfileController@profile')
    ->name('profile.view')
    ->where('username', 'YOUR REGEX HERE');

我会选择您展示的并且已经可以使用的那个:

Route::get('profile/{username}', 'ProfileController@profile')
    ->name('profile.view');

// or
Route::get('user/{username}', 'ProfileController@profile')
    ->name('profile.view');

推荐阅读