Skip to content

Commit

Permalink
Added Slugify
Browse files Browse the repository at this point in the history
  • Loading branch information
nunoxavier committed Oct 3, 2024
1 parent ca86b05 commit 0d68b03
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/Concerns/HasSlug.php
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(' '));
}
});
}
}
13 changes: 13 additions & 0 deletions src/Contracts/ImplementsSlug.php
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;
}

0 comments on commit 0d68b03

Please sign in to comment.