22
votes

I'm doing the following in the

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

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

When I run it in tinker, I get the following error:

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

..but I don't know the Laravel way to import it. Do I need to just use use, I tried to add the following to the config/app.php file:

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

.. didn't seem to make much difference though.

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

6
str_slug($title, $separator); didn't work for you ?Mohamed Kawsara

6 Answers

57
votes

I don't think you need to create alias here, so just add

use Illuminate\Support\Str;

to your model.

11
votes

Edit: As samiles pointed out, str_slug($text) has been removed in Laravel 6.0.

In Laravel 5 you can use str_slug($text) directly. You no longer have to use the Facade.

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

4
votes

I had the exact same issue. Adding the line to aliases in the app\config\app.php file is the correct way to fix this.

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

Doing it this way avoids:

  1. the need to add a use Illuminate\Support\Str; line in your blade file
  2. the need to fully quality the class, i.e \Illuminate\Support\Str::slug($tag->name)

In fact you can see that Mr. Otwell includes this line in Laravel 5.8.

I'm not sure why this didn't work for you. It could be that your Laravel is out of date. Make sure you've upgraded to 5.8 and then run composer update.

1
votes

you can call it by \Str::slug(); you dont have to register an alias to make it works, the Str class is not a facades, but a real static class

0
votes

In laravel version 5.4, write like

Str::slug()
0
votes

In laravel 5 is simpler, you can use these helpers:

Before Laravel 5.8 (from this version is deprecated):

str_slug($tag->name);

After Laravel 5.4:

Str::slug($tag->name)