'I am having issue while keeping the same slug if we don't change title while updating

I am having issue while keeping the same slug if we don't change title while updating, slug take the value of title. I have made a function to create slug. But when i update the same function automatically changes slug because it already exists in DB.

public function createSlug($title, $id = 0)
{
    $slug = str_slug($title);
    $allSlugs = $this->getRelatedSlugs($slug, $id);
    if (! $allSlugs->contains('slug', $slug)){
        return $slug;
    }

    $i = 1;
    $is_contain = true;
    do {
        $newSlug = $slug . '-' . $i;
        if (!$allSlugs->contains('slug', $newSlug)) {
            $is_contain = false;
            return $newSlug;
        }
        $i++;
    } while ($is_contain);
}

// slug function
protected function getRelatedSlugs($slug, $id = 0)
{
    return Post::select('slug')
    ->where('slug', 'like', $slug.'%')
    ->where('id', '<>', $id)
    ->get();
}


Solution 1:[1]

First of all, you don't need to create a function for that. Just validation will be enough.

use Illuminate\Support\Str;

    $validator = $request->validate([
        'slug' => ['required''unique:post'],
    ]);

    if ($validator->fails()) {
        $generate_extension = Str::random(3);;
    }
    $newSlug = str_slug($request->title).'-'.$generate_extension;

Then assign the slug.

$post->slug  = $newSlug;

In order to keep the same slug you can check if title is changed;

    if($post->slug != str_slug($request->title)){
        $post->slug = str_slug($request->title);
    }

or

    if($post->title != $request->title){
        $post->slug = str_slug($request->title);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1