Skip to content

Commit 954bc90

Browse files
committed
retrieve slug from slugs table if the $slugAttribute field was not changed
1 parent 53f59c3 commit 954bc90

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

Diff for: src/Models/Behaviors/HasSlug.php

+23-4
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,10 @@ public function restoreSlugs(): void
124124
*/
125125
public function handleSlugsOnSave(): void
126126
{
127-
$this->disableLocaleSlugs();
128-
129127
$slugParams = $this->twillSlugData !== [] ? $this->twillSlugData : $this->getSlugParams();
130128

129+
$this->disableLocaleSlugs();
130+
131131
foreach ($slugParams as $params) {
132132
if (in_array($params['locale'], config('twill.slug_utf8_languages', []))) {
133133
$params['slug'] = $this->getUtf8Slug($params['slug']);
@@ -358,9 +358,13 @@ public function getSlugParams(?string $locale = null): ?array
358358
throw new \Exception("You must define the field {$slugAttribute} in your model");
359359
}
360360

361+
$slug = $this->getSlugValue($slugAttribute, $translation->locale)
362+
?? $translation->$slugAttribute
363+
?? $this->$slugAttribute;
364+
361365
$slugParam = [
362366
'active' => $translation->active ?? true,
363-
'slug' => $translation->$slugAttribute ?? $this->$slugAttribute,
367+
'slug' => $slug,
364368
'locale' => $translation->locale,
365369
] + $slugDependenciesAttributes;
366370

@@ -400,7 +404,7 @@ public function getSingleSlugParams(?string $locale = null): ?array
400404

401405
$slugParam = [
402406
'active' => 1,
403-
'slug' => $this->$slugAttribute,
407+
'slug' => $this->getSlugValue($slugAttribute, $appLocale) ?? $this->$slugAttribute,
404408
'locale' => $appLocale,
405409
] + $slugDependenciesAttributes;
406410

@@ -415,6 +419,21 @@ public function getSingleSlugParams(?string $locale = null): ?array
415419
return $locale === null ? $slugParams : null;
416420
}
417421

422+
/**
423+
* Returns changed value of slugAttribute field or previous slug value
424+
*
425+
* @param $slugAttribute
426+
* @param $locale
427+
* @return mixed|null
428+
*/
429+
private function getSlugValue($slugAttribute, $locale): mixed
430+
{
431+
return $this->wasChanged($slugAttribute)
432+
? $this->$slugAttribute
433+
: $this->slugs()->where('locale', $locale)
434+
->where('active', true)->value('slug');
435+
}
436+
418437
/**
419438
* Returns the database table name for this model's slugs.
420439
*/

0 commit comments

Comments
 (0)