Laravel model trait to create unique slugs

Home   »   Laravel model trait to create unique slugs

slug) ? $model->slugify($model) : $model->slug;
            $model->slug = $model->createUniqueSlug($slug);
        });
    }

    /**
     * Create a unique slug.
     * @param string $title
     * @return string
     */
    protected function createUniqueSlug(string $title): string
    {
        $slug = Str::slug($title);

        $model = static::query()
            ->where('slug', 'REGEXP', "$slug(\-\d+)?")
            ->orderBy('slug', 'desc')
            ->first(['slug']);

        if ($model) {
            if (preg_match("#(-\d+)$#", $model->slug, $matches)) {
                $index = (int)str_replace('-', '', $matches[1]);
                return $slug . '-' . ($index + 1);
            }
            return "$slug-1";
        }

        return $slug;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *