2026-02-06 14:56:56 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Models;
|
|
|
|
|
|
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
2026-02-21 14:57:38 +02:00
|
|
|
use Illuminate\Support\Str;
|
2026-02-06 14:56:56 +02:00
|
|
|
|
|
|
|
|
class Category extends Model
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* The attributes that are mass assignable.
|
|
|
|
|
*
|
|
|
|
|
* @var array<int, string>
|
|
|
|
|
*/
|
|
|
|
|
protected $fillable = [
|
|
|
|
|
'name',
|
|
|
|
|
'slug',
|
|
|
|
|
'description',
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get the products for the category.
|
|
|
|
|
*/
|
|
|
|
|
public function products(): HasMany
|
|
|
|
|
{
|
|
|
|
|
return $this->hasMany(Product::class);
|
|
|
|
|
}
|
2026-02-21 14:57:38 +02:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Generate a unique slug for the category based on its name.
|
|
|
|
|
*/
|
|
|
|
|
public static function generateUniqueSlug(string $name, ?int $excludeId = null): string
|
|
|
|
|
{
|
|
|
|
|
$slug = Str::slug($name);
|
|
|
|
|
$originalSlug = $slug;
|
|
|
|
|
$count = 1;
|
|
|
|
|
|
|
|
|
|
// Keep appending numbers until we find a unique slug
|
|
|
|
|
$query = static::where('slug', $slug);
|
|
|
|
|
if ($excludeId) {
|
|
|
|
|
$query->where('id', '!=', $excludeId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
while ($query->exists()) {
|
|
|
|
|
$slug = $originalSlug . '-' . $count;
|
|
|
|
|
$count++;
|
|
|
|
|
$query = static::where('slug', $slug);
|
|
|
|
|
if ($excludeId) {
|
|
|
|
|
$query->where('id', '!=', $excludeId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $slug;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get the route key for the model.
|
|
|
|
|
*/
|
|
|
|
|
public function getRouteKeyName(): string
|
|
|
|
|
{
|
|
|
|
|
return 'slug';
|
|
|
|
|
}
|
2026-02-06 14:56:56 +02:00
|
|
|
}
|