【问题标题】:How to use Illuminate\Support\Str::slug in my Laravel 5 app?如何在我的 Laravel 5 应用程序中使用 Illuminate\Support\Str::slug?
【发布时间】:2015-05-30 14:52:54
【问题描述】:

我在做下面的

public function boot(DispatcherContract $events)
{
    parent::boot($events);

    // set Tag slug
    Tag::saving(function($tag)
    {
        //slugify name
        $tag->slug = Str::slug($tag->name);
    });
}

当我在 tinker 中运行它时,我收到以下错误:

PHP Fatal error:  Class 'App\Providers\Str' not found in /var/www/questions-l5/app/Providers/EventServiceProvider.php on line 35

..但我不知道 Laravel 的导入方式。我是否只需要使用use,我尝试将以下内容添加到 config/app.php 文件中:

'aliases' => [
...
'Str'      => 'Illuminate\Support\Str',

.. 不过好像没什么区别。

http://chrishayes.ca/blog/code/laravel-4-generating-unique-slugs-elegantly http://laravel.com/api/5.0/Illuminate/Support/Str.html

【问题讨论】:

  • str_slug($title, $separator); 不适合你?

标签: php laravel laravel-5


【解决方案1】:

我遇到了完全相同的问题。将这一行添加到 app\config\app.php 文件中的别名是解决此问题的正确方法。

'alias' => [
     ...
     'Str' => Illuminate\Support\Str::class,
     ...
],

这样做可以避免:

  1. 需要在您的刀片文件中添加 use Illuminate\Support\Str;
  2. 需要完全质量类,即\Illuminate\Support\Str::slug($tag->name)

实际上你可以看到 Mr. Otwell 在Laravel 5.8 中包含了这一行。

我不确定为什么这对您不起作用。可能是你的 Laravel 已经过时了。确保您已升级到 5.8,然后运行 ​​composer update

【讨论】:

    【解决方案2】:

    在 laravel 5 中更简单,你可以使用这些助手:

    在 Laravel 5.8 之前(从此版本已弃用):

    str_slug($tag->name);
    

    在 Laravel 5.4 之后:

    Str::slug($tag->name)
    

    【讨论】:

    【解决方案3】:

    编辑:正如 samiles 指出的,str_slug($text) 已在 Laravel 6.0 中删除。

    在 Laravel 5 中你可以直接使用str_slug($text)。您不再需要使用 Facade。

    http://laravel.com/docs/5.1/helpers#method-str-slug

    【讨论】:

    【解决方案4】:

    在laravel 5.4版本中,写成这样

    Str::slug()
    

    【讨论】:

      【解决方案5】:

      你可以通过 \Str::slug(); 调用它。 您不必注册别名即可使其工作,Str 类不是外观,而是真正的静态类

      【讨论】:

        【解决方案6】:

        我认为你不需要在这里创建别名,所以只需添加

        use Illuminate\Support\Str;
        

        到你的模型。

        【讨论】:

        • 或者更好的是,您可以添加外观,只需在您将使用它的文件顶部添加use Str;
        • Limonte,如何在刀片文件中使用 Str? {{ use Illuminate\Support\Str; }} 给出错误。
        • str_slug 在 Laravel 5.8 中被弃用,在 5.9 中被移除。在控制器、模型中,您只需添加:use Illuminate\Support\Str; 在刀片/视图中,您可以添加 {{ \Illuminate\Support\Str::slug($title) }}
        • 门面是默认加载的,所以你可以在刀片文件中使用Str::slug($title)
        猜你喜欢
        • 2014-08-19
        • 2017-11-03
        • 2015-06-15
        • 2021-08-30
        • 2022-06-14
        • 2015-01-14
        • 1970-01-01
        • 2021-12-09
        相关资源
        最近更新 更多