Skip to content

Instantly share code, notes, and snippets.

@hose1021
Created October 17, 2021 20:55
Show Gist options
  • Save hose1021/0c9040b6e2df5678640f483a068184c5 to your computer and use it in GitHub Desktop.
Save hose1021/0c9040b6e2df5678640f483a068184c5 to your computer and use it in GitHub Desktop.

Revisions

  1. hose1021 renamed this gist Oct 17, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. hose1021 created this gist Oct 17, 2021.
    47 changes: 47 additions & 0 deletions HasSlug
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    <?php

    namespace Shopper\Framework\Models\Traits;

    use Illuminate\Support\Str;

    trait HasSlug
    {
    public function slug(): string
    {
    return $this->slug;
    }

    public function setSlugAttribute(string $slug)
    {
    $this->attributes['slug'] = $this->generateUniqueSlug($slug);
    }

    public static function findBySlug(string $slug): self
    {
    return static::where('slug', $slug)->firstOrFail();
    }

    protected function generateUniqueSlug(string $value): string
    {
    $slug = $originalSlug = Str::slug($value) ?: Str::random(5);
    $counter = 0;

    while ($this->slugExists($slug, $this->exists ? $this->id : null)) {
    $counter++;
    $slug = $originalSlug . '-' . $counter;
    }

    return $slug;
    }

    private function slugExists(string $slug, ?int $ignoreId = null): bool
    {
    $query = $this->where('slug', $slug);

    if ($ignoreId) {
    $query->where('id', '!=', $ignoreId);
    }

    return $query->exists();
    }
    }