【问题标题】:Create title slug + random string Laravel 7创建标题 slug + 随机字符串 Laravel 7
【发布时间】:2020-08-29 18:25:06
【问题描述】:

我想在 Laravel 中创建一个结合标题 + 随机字符串的 slug。

我试过了,但什么都没有,在第二种情况下,它什么都不做,只是将字符串与标题结合起来。

Str::slug(request('title'), '-', Str::random());

Str::slug(request('title'), Str::random());

我想要这样的东西:

this-is-an-example-title-Jfij4jio4523q234

【问题讨论】:

    标签: laravel title slug


    【解决方案1】:

    仔细检查来自https://laravel.com/docs/7.x/helpers#method-str-slug 的方法签名(更深入地检查https://github.com/laravel/framework/blob/7.x/src/Illuminate/Support/Str.php#L552

    明确地说,该方法的第二个参数是用于替换空格的字符,第三个参数是指生成 slug 时使用的语言环境。这意味着在将字符串传递给方法之前,您需要完全组合字符串。

    假设您希望通过- 加入您的 slug,那么您想要的是这样的:

    $value = request('title') . ' ' . Str::random();
    $slug = Str::slug($value); // optionally Str::slug($value, '-'); to explicitly define the join
    

    【讨论】:

    • 或在方法调用中连接,如Str::slug(request('title') . ' ' . Str::random());,无论是更清洁/首选。
    【解决方案2】:

    Str::Slug() 已定义为:

    slug(string $title, string $separator = '-', string $language = 'en')
    

    第三个参数可以看成language,默认值:en

    Str::slug($request->input('title').Str::random(40), '-');
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2011-02-28
      • 2014-10-20
      • 1970-01-01
      • 2011-02-21
      相关资源
      最近更新 更多