Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique slug to same post-title for other time too?

Tags:

php

laravel

I have tried the codes as follows.

 $post->title = $request->title;
        $post->body = $request->body;
        $post->slug  = str_slug($post->title,'%');

The code was running great but now I have the post with same title so its throwing error as it is set to unique in db. Is there any way I can get another slug?

like image 295
Sushila Singh Avatar asked Jan 15 '18 13:01

Sushila Singh


1 Answers

If you are facing a slug colision, in this case best way to go would be adding an extra integer at the end example :

mysite.dev/my-post
mysite.dev/my-post-1

For this you could use a package to generate a slug

Of if you want to do it yourself then in the model add slugattribute

public function setSlugAttribute($value) {

    if (static::whereSlug($slug = str_slug($value))->exists()) {

        $slug = $this->incrementSlug($slug);
    }

    $this->attributes['slug'] = $slug;
}

So the setSlugAtrribute will always check if the slug for given model exists if so then it will increment the slug as I meantioned above, by simply calling the below method.

public function incrementSlug($slug) {

    $original = $slug;

    $count = 2;

    while (static::whereSlug($slug)->exists()) {

        $slug = "{$original}-" . $count++;
    }

    return $slug;

}

Basically we are always checking if the slug exists in the database, if yes then we use an accessor to change the slug by adding an integer at the end this way you will never end having the slug duplication issue.

like image 161
Leo Avatar answered Sep 28 '22 01:09

Leo