Skip to content

Commit

Permalink
retrieve slug from slugs table if the $slugAttribute field was not ch…
Browse files Browse the repository at this point in the history
…anged
  • Loading branch information
zeezo887 committed Nov 1, 2024
1 parent 53f59c3 commit 954bc90
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/Models/Behaviors/HasSlug.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,10 @@ public function restoreSlugs(): void
*/
public function handleSlugsOnSave(): void
{
$this->disableLocaleSlugs();

$slugParams = $this->twillSlugData !== [] ? $this->twillSlugData : $this->getSlugParams();

$this->disableLocaleSlugs();

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

$slug = $this->getSlugValue($slugAttribute, $translation->locale)
?? $translation->$slugAttribute
?? $this->$slugAttribute;

$slugParam = [
'active' => $translation->active ?? true,
'slug' => $translation->$slugAttribute ?? $this->$slugAttribute,
'slug' => $slug,
'locale' => $translation->locale,
] + $slugDependenciesAttributes;

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

$slugParam = [
'active' => 1,
'slug' => $this->$slugAttribute,
'slug' => $this->getSlugValue($slugAttribute, $appLocale) ?? $this->$slugAttribute,
'locale' => $appLocale,
] + $slugDependenciesAttributes;

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

/**
* Returns changed value of slugAttribute field or previous slug value
*
* @param $slugAttribute
* @param $locale
* @return mixed|null
*/
private function getSlugValue($slugAttribute, $locale): mixed
{
return $this->wasChanged($slugAttribute)
? $this->$slugAttribute
: $this->slugs()->where('locale', $locale)
->where('active', true)->value('slug');
}

/**
* Returns the database table name for this model's slugs.
*/
Expand Down

0 comments on commit 954bc90

Please sign in to comment.