-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ca86b05
commit 0d68b03
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
<?php | ||
|
||
namespace Flavorly\LaravelHelpers\Concerns; | ||
|
||
use Flavorly\LaravelHelpers\Contracts\ImplementsSlug; | ||
use Illuminate\Database\Eloquent\Model; | ||
use Illuminate\Support\Str; | ||
|
||
/** | ||
* Usage on Model: | ||
* | ||
* use Flavorly\LaravelHelpers\Concerns\HasSlug; | ||
* | ||
* public function getSlugAttributes(): array | ||
* { | ||
* return [ | ||
* 'name', 'relation.slug', // relation property | ||
* // or 'name', 'id', etc | ||
* ]; | ||
* } | ||
*/ | ||
trait HasSlug | ||
{ | ||
public static function bootHasSlug(): void | ||
{ | ||
static::creating(function (Model&ImplementsSlug $model) { | ||
$model->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(' ')); | ||
} | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
|
||
namespace Flavorly\LaravelHelpers\Contracts; | ||
|
||
interface ImplementsSlug | ||
{ | ||
/** | ||
* Get list of attributes that should be used to generate the slug | ||
* | ||
* @return string[] | ||
*/ | ||
public function getSlugAttributes(): array; | ||
} |