@@ -23,7 +23,7 @@ public static function bootHasSlug()
23
23
if (!is_null ($ model ->$ attribute )) return ;
24
24
25
25
$ sluggable = $ model ->getSluggable ();
26
- $ model ->attributes [$ attribute ] = str_slug ($ model ->$ sluggable );
26
+ $ model ->attributes [$ attribute ] = $ model -> getUniqueSlug ($ model ->$ sluggable );
27
27
}
28
28
});
29
29
}
@@ -42,13 +42,67 @@ public function translateSlugs($attribute)
42
42
43
43
foreach ($ this ->getTranslatedLocales ($ this ->getSluggable ()) as $ locale ) {
44
44
if (!isset ($ value [$ locale ]) || is_null ($ value [$ locale ])) {
45
- $ value [$ locale ] = str_slug ( $ this ->getTranslation ($ sluggable , $ locale) );
45
+ $ value [$ locale ] = $ this ->getUniqueSlug ($ sluggable , $ locale );
46
46
}
47
47
}
48
48
49
49
$ this ->attributes [$ attribute ] = json_encode ($ value );
50
50
}
51
51
52
+ /**
53
+ * Get a unique slug
54
+ *
55
+ * @param string $value
56
+ * @param string|null $locale
57
+ * @return string
58
+ */
59
+ public function getUniqueSlug ($ sluggable , $ locale = null )
60
+ {
61
+ if (!is_null ($ locale )) {
62
+ $ sluggable = $ this ->getTranslation ($ sluggable , $ locale );
63
+ }
64
+
65
+ $ slug = str_slug ($ sluggable );
66
+
67
+ $ i = 1 ;
68
+ while ($ this ->slugExists ($ slug , $ locale )) {
69
+ $ slug = $ slug . '- ' . $ i ;
70
+ }
71
+
72
+ return $ slug ;
73
+ }
74
+
75
+ /**
76
+ * Check if the slug exists (for the given locale if any)
77
+ *
78
+ * @param string $slug
79
+ * @param string|null $locale
80
+ * @return bool
81
+ */
82
+ public function slugExists ($ slug , $ locale = null )
83
+ {
84
+ $ whereKey = is_null ($ locale ) ? $ this ->getSlugStorageAttribute () : $ this ->getSlugStorageAttribute ().'-> ' .$ locale ;
85
+
86
+ $ query = static ::where ($ whereKey , $ slug )
87
+ ->withoutGlobalScopes ();
88
+
89
+ if ($ this ->usesSoftDeletes ()) {
90
+ $ query ->withTrashed ();
91
+ }
92
+
93
+ return $ query ->exists ();
94
+ }
95
+
96
+ /**
97
+ * Check if model uses soft deletes
98
+ *
99
+ * @return bool
100
+ */
101
+ protected function usesSoftDeletes (): bool
102
+ {
103
+ return (bool ) in_array ('Illuminate\Database\Eloquent\SoftDeletes ' , class_uses ($ this ));
104
+ }
105
+
52
106
/**
53
107
* Get the attribute name used to generate the slug from
54
108
*
0 commit comments