Search code examples
phplaravelslug

Laravel Slug Exist


I want to create slug for blog categories. I do it like this;

Str::slug($request->title)

But I have to check if slug exist. If exist, I want to do like this;

// For example title is test. Slug must be test.
// But if slug exist I want to do it test1
if(count(blog_tags::where('slug',$slug)->get()) > 0){
     $slug = $slug . '1';
}
// But test1 too can be exist. So I have to test it.

If I test it again and again, system will be slow. What should I do?


Solution

  • Add the following function in your controller class to check ending number in slug

    protected function countEndingDigits($string)
    {
        $tailing_number_digits =  0;
        $i = 0;
        $from_end = -1;
        while ($i < strlen($string)) :
          if (is_numeric(substr($string, $from_end - $i, 1))) :
            $tailing_number_digits++;
          else :
            // End our while if we don't find a number anymore
            break;
          endif;
          $i++;
        endwhile;
        return $tailing_number_digits;
    }
    

    Add the following function in your controller class to check slug already exists or not

    protected function checkSlug($slug) {
    
    if(blog_tags::where('slug',$slug)->count() > 0){
     $numIn = $this->countEndingDigits($slug);
     if ($numInUN > 0) {
              $base_portion = substr($slug, 0, -$numInUN);
              $digits_portion = abs(substr($slug, -$numInUN));
      } else {
              $base_portion = $slug . "-";
              $digits_portion = 0;
      }
    
      $slug = $base_portion . intval($digits_portion + 1);
      $slug = $this->checkSlug($slug)
    }
    
    return $slug
    }
    

    Now you will get a unique incremental slug

    $slug = $this->checkSlug(Str::slug(string));