From 06238436e5a26838dd4fe3d80bca6fe4a95af4da Mon Sep 17 00:00:00 2001 From: gregupton Date: Thu, 11 Jul 2024 14:40:06 -0400 Subject: [PATCH] WIP --- CHANGELOG.md | 3 +++ src/Traits/Sluggable.php | 36 ++++++++++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93961cb..8e77b70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # Change Log All notable changes to `sluggable` will be documented in this file. +## 1.0.5 - 2024-07-11 +- Fixed issue where the slug was changing on all updates. Now only changes if the source field changes. + ## 1.0.4 - 2024-07-08 - Fixed where I completely f'd the service provider in the last update. diff --git a/src/Traits/Sluggable.php b/src/Traits/Sluggable.php index 3f62a9d..25e5ee7 100644 --- a/src/Traits/Sluggable.php +++ b/src/Traits/Sluggable.php @@ -14,8 +14,12 @@ trait Sluggable */ public static function bootSluggable(): void { - static::saving(function ($model) { - $model->generateSlug(); + static::creating(function ($model) { + $model->generateSlugOnCreate(); + }); + + static::updating(function ($model) { + $model->generateSlugOnUpdate(); }); } @@ -25,17 +29,17 @@ public static function bootSluggable(): void * @param string $slug * @return Model|null */ - public static function findBySlug($slug) + public static function findBySlug($slug): ?Model { return static::where('slug', $slug)->first(); } /** - * Generate a unique slug for the model. + * Generate a unique slug for the model on creation. * * @return void */ - protected function generateSlug(): void + protected function generateSlugOnCreate(): void { $slug = Str::slug($this->getSlugSource()); @@ -45,12 +49,32 @@ protected function generateSlug(): void $this->slug = $slug; } + /** + * Generate a unique slug for the model on update. + * + * @return void + */ + protected function generateSlugOnUpdate(): void + { + $slugSource = $this->getSlugSource(); + + // Check if the slug source field has changed + if ($this->isDirty($this->slugSource)) { + $slug = Str::slug($slugSource); + + // Ensure the slug is unique + $slug = $this->makeSlugUnique($slug); + + $this->slug = $slug; + } + } + /** * Get the source string for the slug. * * @return string */ - protected function getSlugSource() + protected function getSlugSource(): string { if (property_exists($this, 'slugSource')) { return $this->{$this->slugSource};