Bribin's avatar

Generate a Unique slug From Title

Please help me to generate a Unique Slug From Title

0 likes
13 replies
sitesense's avatar

Generating a URL friendly slug using a given separator:

$slug = Str::slug('My Page Title', '_');
1 like
uxweb's avatar

You can use the Str class shipped with laravel:

Str::slug($request->get('title'));

Bribin's avatar

@sitesense

I Tried this method. but im getting this Error

FatalErrorException in PageController.php line 63: Class 'Str' not found

sitesense's avatar
Level 19

Try this then:

$slug = \Str::slug('My Page Title', '_');

It depends where it's called from with regards to namespacing.

5 likes
Bribin's avatar

@sitesense Thanks for Replay .. This also i tried . again im getting the same Error :(

sitesense's avatar

@bribin ah you might want to add this to your aliases array in config/app.php:

'Str'       => 'Illuminate\Support\Str',
joedawson's avatar

I use this method on my Model - a slug is automatically generated each time the model is saved.

public static function boot()
{
    parent::boot();

    static::saving(function($model) {
        $model->slug = str_slug($model->title);

        return true;
    });
}
2 likes
Ncls's avatar

What happens here when you do something like (on a create method):

$slug = str_slug($project); .

And you try to enter a project by the same name. Will it throw errors, or will it just make a slug with an identifier (ex:project-2) at the end?

PS: slug is set to unique in model/migration

Nick385's avatar

I was trying this lesson https://laracasts.com/lessons/unique-slugs-in-laravel To make it work change this

static::whereRaw("slug REGEXP '^{$model->slug}(-[0-9]*)?$'")

To

static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")

Complete code put this on you're model

   public static function boot()
   {
       parent::boot();

       static::creating(function($model) {
           $model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied

           $latestSlug =
               static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
                   ->latest('id')
                   ->value('slug');
           if ($latestSlug) {
               $pieces = explode('-', $latestSlug);

               $number = intval(end($pieces));

               $model->slug .= '-' . ($number + 1);
           }
       });
   }
2 likes
chhorvon's avatar
Laravel 5.6
use Illuminate\Support\Str;

$slug = Str::slug('My Page Title', '_');

it work for me

Please or to participate in this conversation.