Skip to content

Commit

Permalink
Merge pull request #4 from AesirCloud/1.0.5
Browse files Browse the repository at this point in the history
WIP
  • Loading branch information
gregupton authored Jul 11, 2024
2 parents 8a6d814 + 0623843 commit 01e85c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down
36 changes: 30 additions & 6 deletions src/Traits/Sluggable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
}

Expand All @@ -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());

Expand All @@ -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};
Expand Down

0 comments on commit 01e85c7

Please sign in to comment.