presseportale/app/Models/CategoryTranslation.php
Kevin Adametz 5b8bdf4182
Some checks are pending
linter / quality (push) Waiting to run
tests / ci (push) Waiting to run
12-05-2026 Frontend dev
2026-05-12 18:32:33 +02:00

51 lines
1.3 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
class CategoryTranslation extends Model
{
protected $fillable = [
'category_id',
'locale',
'name',
'slug',
'description',
];
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
/**
* Generates a slug that is unique within a single locale.
* If `$ignoreCategoryId` is given (when editing), a clash with this very
* category's translation is allowed, so renaming back to the same slug
* works.
*/
public static function uniqueSlug(string $source, string $locale, ?int $ignoreCategoryId = null): string
{
$base = Str::slug($source) ?: 'kategorie';
$slug = $base;
$i = 2;
while (
self::query()
->where('locale', $locale)
->where('slug', $slug)
->when(
$ignoreCategoryId !== null,
fn ($q) => $q->where('category_id', '!=', $ignoreCategoryId),
)
->exists()
) {
$slug = $base.'-'.$i++;
}
return $slug;
}
}