【问题标题】:Laravel routes for user profiles? without /user用户个人资料的 Laravel 路线?没有/用户
【发布时间】:2015-05-10 05:58:56
【问题描述】:

在 Laravel 路由中:

我想让有 URL 的个人资料用户:example.com/steve

其实我有:example.com/user/steve

当我进行路由更新时,这可行:

Route::get('{username}', ['as' => 'profile', 'uses' => 'ProfileController@show']);

但是当我尝试进入另一条路线(/guide)时:

Route::get('guide', ['as' => 'guide', 'uses' => 'GuestController@showGuide']);

这与用户配置文件路线“崩溃”。我怎样才能让它在没有 404 错误的情况下工作?

我想尝试一种与“i 方法”不同的方法(将字母 i 放在所有 URL 之前:Route::get('i/guide'))

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    Laravel 从上到下匹配列出的路由。所以\{username} 将匹配\{anyword}

    解决此问题的方法之一是;

    在你的 routes.php 中 Route::get('guide', ['as' => 'guide', 'uses' => 'GuestController@showGuide']); 应该排在第一位。

    Route::get('{username}', ['as' => 'profile', 'uses' => 'ProfileController@show']); 放置在其他路由之后

    【讨论】:

      【解决方案2】:

      您应该首先创建指南的路线

      Route::get('guide', ['as' => 'guide', 'uses' => 'GuestController@showGuide']);
      

      然后是用户

      Route::get('{username}', ['as' => 'profile', 'uses' => 'ProfileController@show']);
      

      routes.php 文件中的顺序很重要。如果 {username} 路线高于指南路线,那么它会将指南视为 {username} 并相应地重定向您,但您没有用户名指南的用户

      【讨论】:

        【解决方案3】:
        Route::group(['prefix' => 'i'], function()
        {
            Route::get('guide', function()
            {
                // Matches The "/i/guide" URL
            });
        });
        

        对路由进行分组并为其添加前缀。

        【讨论】:

          猜你喜欢
          • 2020-05-20
          • 1970-01-01
          • 2020-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-06
          • 2018-09-27
          相关资源
          最近更新 更多