SlugTrait

0
Trait для удобства работы с моделями в которых есть поле slug|alias
app/Models/Traits/SlugTrait.php
                            
<?php
 
namespace App\Models\Traits;
 
use Illuminate\Support\Str;
 
trait SlugTrait
{
public function slug()
{
return $this->slug;
}
 
public function setSlugAttribute($slug)
{
$this->attributes['slug'] = $this->uniqueSlug($slug);
}
 
public static function findBySlug(string $slug)
{
return static::where('slug', $slug)->firstOrFail();
}
 
private function uniqueSlug(string $value): string
{
$slug = $value ? Str::slug($value) : Str::random(5);
 
while ($this->slugExists($slug, $this->exists() ? $this->id() : null)) {
$slug = $slug . '-' . Str::random(5);
}
 
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();
}
}