@@ -56,16 +56,45 @@ public function generate(): string
5656 $ slug = $ this ->slugify ($ this ->resolveSourceValue ());
5757
5858 if ($ slug === '' ) {
59- $ columns = implode (', ' , Arr::wrap ($ this ->options ()->from ));
60-
61- throw new CouldNotGenerateSlugException (
62- 'Could not generate a slug for [ ' .get_class ($ this ->model )."] using column(s) [ {$ columns }]. "
63- );
59+ $ this ->throwEmptySlugException ();
6460 }
6561
6662 return $ this ->ensureUnique ($ slug );
6763 }
6864
65+ /**
66+ * Throw an exception when the slug source produces an empty slug.
67+ *
68+ * @throws EmptySlugException
69+ */
70+ protected function throwEmptySlugException (): void
71+ {
72+ $ options = $ this ->options ();
73+ $ from = Arr::wrap ($ options ->from );
74+ $ errorKey = $ options ->errorKey ?? $ from [0 ];
75+ $ columns = implode (', ' , $ from );
76+
77+ throw new EmptySlugException (
78+ "Could not generate a slug for [ " .get_class ($ this ->model )."] using column(s) [ {$ columns }]. " ,
79+ $ errorKey ,
80+ $ this ->resolveErrorMessage ($ errorKey , $ options ),
81+ );
82+ }
83+
84+ /**
85+ * Resolve the user-facing error message for a failed slug generation.
86+ */
87+ protected function resolveErrorMessage (string $ errorKey , Sluggable $ options ): string
88+ {
89+ $ from = Arr::wrap ($ options ->from );
90+ $ attribute = count ($ from ) === 1 ? $ from [0 ] : implode (' and ' , [implode (', ' , array_slice ($ from , 0 , -1 )), end ($ from )]);
91+ $ replacements = ['attribute ' => $ attribute , 'column ' => $ options ->column ];
92+
93+ return $ options ->errorMessage
94+ ? __ ($ options ->errorMessage , $ replacements )
95+ : __ ('validation.sluggable ' , $ replacements );
96+ }
97+
6998 /**
7099 * Determine if the slug source columns have changed.
71100 */
@@ -153,8 +182,12 @@ protected function ensureUnique(string $slug): string
153182 $ count ++;
154183
155184 if ($ count > $ options ->maxAttempts ) {
185+ $ errorKey = $ options ->errorKey ?? $ options ->column ;
186+
156187 throw new CouldNotGenerateSlugException (
157- 'Could not generate a unique slug for [ ' .get_class ($ this ->model )."] with base [ {$ originalSlug }] after {$ options ->maxAttempts } attempts. "
188+ 'Could not generate a unique slug for [ ' .get_class ($ this ->model )."] with base [ {$ originalSlug }] after {$ options ->maxAttempts } attempts. " ,
189+ $ errorKey ,
190+ $ this ->resolveErrorMessage ($ errorKey , $ options ),
158191 );
159192 }
160193
0 commit comments