Laravel 鼻涕虫存在

Laravel Slug Exist

我想为博客类别创建 slug。我是这样做的;

Str::slug($request->title)

但我必须检查是否存在 slug。如果存在,我想这样做;

// 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.

如果我反复测试,系统会很慢。我该怎么办?

在您的控制器中添加以下功能class以检查 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;
}

在您的控制器中添加以下功能class 以检查 slug 是否已经存在

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
}

现在您将获得一个独特的增量弹头

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