51 lines
1.3 KiB
PHP
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;
|
|
}
|
|
}
|