【问题标题】:Laravel 5 make routing with unique parameterLaravel 5 使用唯一参数进行路由
【发布时间】:2018-05-18 20:29:59
【问题描述】:

我目前正在使用带有参数name的路由来查询我的应用程序中用户的个人资料。

例如:/members/john将显示约翰的个人资料。

您在这里看到了问题,如果有 2 个约翰,那就是个问题。

我知道我可以做这样的事情 /members/idsince id 是唯一的,但我希望 url 看起来很漂亮,带有用户名而不是随机数。

所以我的问题是,是否有办法使用 id 使其唯一但在 url 中显示名称?

我的路线:

Route::get('/members/{name}', 'UserController@usersProfile');

我的 usersProfile 方法:

/**
 * Returns a users profile.
 *
 * @param string $name
 *
 * @return \Illuminate\Http\Response
 */
public function usersProfile($name)
{
    $profile = $this->userService->getProfile($name);

    if ($profile == null) {
        return redirect('members')->with('status', 'Whoops, looks like that member does not exist (yet).');
    }

    return view('members/profile', ['profile' => $profile]);
}

【问题讨论】:

  • 为每个用户创建一个唯一的用户名并在路由中使用该值
  • @MKhalidJunaid 感谢您的回复,但我不想使用唯一的用户名。
  • 也取决于这个想法......是否有人真的会输入一个 URL......如果你这么认为,那么这个命名的东西很重要,如果不是那么没关系@987654326 @ 现在不可能发生冲突,并且名称仍在 URL 中
  • 你也不想使用 id 那么如何确定用户呢?
  • 在迁移用户表时确保name字段是唯一的$table->string('name')->unique();

标签: php laravel laravel-5


【解决方案1】:

您可以使用一些包来填写您的型号名称:

https://github.com/spatie/laravel-sluggable

https://github.com/cviebrock/eloquent-sluggable

这些包会自动为你做这些。

如果你有相同的名字,就会发生这种情况:

http://example.com/post/my-dinner-with-andre-francois
http://example.com/post/my-dinner-with-andre-francois-1
http://example.com/post/my-dinner-with-andre-francois-2

只是在生产中,我对范围有些问题... 当您在模型上应用全局范围时,它可能会为此创建重复的 slug ...您可以通过将其添加到模型来解决此问题:

public function scopeFindSimilarSlugs(Builder $query, Model $model, $attribute, $config, $slug)
    {
        $separator = $config['separator'];

        return $query->withoutGlobalScopes()->where(function (Builder $q) use ($attribute, $slug, $separator) {
            $q->where($attribute, '=', $slug)
                ->orWhere($attribute, 'LIKE', $slug . $separator . '%');
        });
    }

【讨论】:

  • 谢谢!很酷的包,正是我需要的。 :)
【解决方案2】:

您应该在您的用户表中添加另一个名为“slug”或“用户名”的列,并将该列映射到您的路线中。

在您的用户模型中,创建一个静态函数来生成带有编号的唯一 slug,并将其保存在该新列中,以便为用户提供公共/私人个人资料 URL。

以下示例将在 100 个同名用户后停止返回 slug/用户名。

public static function getUniqueSlug($name) {
  $original_slug = getSlug($name); // Default getter to get value in model
  $slug = str_slug($original_slug); //Convert a string into url friendly string with hyphens

  while(true) {
    $count = User::where('slug', $slug)->count();
    if($count > 0) {
      $slug = $original_slug."-".rand(1,99);
    } else {
      return $slug;
    }
  }
}

【讨论】:

    猜你喜欢
    • 2015-08-11
    • 2016-08-01
    • 2015-06-25
    • 1970-01-01
    • 2018-11-16
    • 2015-04-17
    • 2018-04-07
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多