From 0d68b03c9f0b81cdba513e41d9376f9f5fd8d32e Mon Sep 17 00:00:00 2001 From: nunoxavier Date: Thu, 3 Oct 2024 13:35:05 +0100 Subject: [PATCH] Added Slugify --- src/Concerns/HasSlug.php | 47 ++++++++++++++++++++++++++++++++ src/Contracts/ImplementsSlug.php | 13 +++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/Concerns/HasSlug.php create mode 100644 src/Contracts/ImplementsSlug.php diff --git a/src/Concerns/HasSlug.php b/src/Concerns/HasSlug.php new file mode 100644 index 0000000..62eea4f --- /dev/null +++ b/src/Concerns/HasSlug.php @@ -0,0 +1,47 @@ +slug = Str::uuid()->toString(); + }); + + static::created(function (Model&ImplementsSlug $model) { + $model->update([ + 'slug' => Str::slug(collect($model->getSlugAttributes()) + ->map(fn (string $attribute) => $model->$attribute) + ->implode(' ')), + ]); + }); + + static::updating(function (Model&ImplementsSlug $model) { + $attributes = $model->getSlugAttributes(); + if ($model->isDirty($attributes)) { + $model->slug = Str::slug(collect($model->getSlugAttributes()) + ->map(fn (string $attribute) => $model->$attribute) + ->implode(' ')); + } + }); + } +} diff --git a/src/Contracts/ImplementsSlug.php b/src/Contracts/ImplementsSlug.php new file mode 100644 index 0000000..433c7ad --- /dev/null +++ b/src/Contracts/ImplementsSlug.php @@ -0,0 +1,13 @@ +