Skip to content

Commit 04dba93

Browse files
authored
Added getSlugExistsQuery method (to allow overriding) & fixed unique slug generation
1 parent 0734d2d commit 04dba93

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/HasSlug.php

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,12 @@ public function getUniqueSlug($sluggable, $locale = null)
6464

6565
$slug = str_slug($sluggable);
6666

67-
$i = 1;
68-
while($this->slugExists($slug, $locale)) {
67+
$i = 0;
68+
while($this->slugExists($slug, $locale, $i)) {
69+
$i++;
70+
}
71+
72+
if ($i) {
6973
$slug = $slug . '-' . $i;
7074
}
7175

@@ -77,14 +81,18 @@ public function getUniqueSlug($sluggable, $locale = null)
7781
*
7882
* @param string $slug
7983
* @param string|null $locale
84+
* @param int $i
8085
* @return bool
8186
*/
82-
public function slugExists($slug, $locale = null)
87+
public function slugExists($slug, $locale = null, $i = 0)
8388
{
8489
$whereKey = is_null($locale) ? $this->getSlugStorageAttribute() : $this->getSlugStorageAttribute().'->'.$locale;
8590

86-
$query = static::where($whereKey, $slug)
87-
->withoutGlobalScopes();
91+
if ($i) {
92+
$slug = $slug . '-' . $i;
93+
}
94+
95+
$query = $this->getSlugExistsQuery($whereKey, $slug);
8896

8997
if ($this->usesSoftDeletes()) {
9098
$query->withTrashed();
@@ -93,6 +101,19 @@ public function slugExists($slug, $locale = null)
93101
return $query->exists();
94102
}
95103

104+
/**
105+
* Get the query that checks if the slug already exists
106+
*
107+
* @param string $whereKey
108+
* @param string $slug
109+
* @return \Illuminate\Database\Eloquent\Builder
110+
*/
111+
protected function getSlugExistsQuery($whereKey, $slug)
112+
{
113+
return $query = static::where($whereKey, $slug)
114+
->withoutGlobalScopes();
115+
}
116+
96117
/**
97118
* Check if model uses soft deletes
98119
*

0 commit comments

Comments
 (0)