Laravel 13 + Filament 5 admin panel and REST API for a non-profit developer collective, backed by the Pireon OAuth identity server. The public site is a separate, server-rendered application consuming /api/public/v1. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
65 lines
1.8 KiB
PHP
65 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/**
|
|
* Enforces slug uniqueness per locale.
|
|
*
|
|
* Slugs live inside a JSON map, which no database unique index can cover, so
|
|
* the check happens here: for each locale in the payload, no *other* row may
|
|
* already use that slug in that same locale. The same slug in two different
|
|
* languages is fine.
|
|
*/
|
|
class UniqueTranslatedSlug implements ValidationRule
|
|
{
|
|
/**
|
|
* @param class-string<Model> $model
|
|
*/
|
|
public function __construct(
|
|
protected string $model,
|
|
protected ?int $ignoreId = null,
|
|
protected string $column = 'slug',
|
|
) {}
|
|
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
$translations = is_string($value)
|
|
? [app()->getLocale() => $value]
|
|
: (array) $value;
|
|
|
|
foreach ($translations as $locale => $slug) {
|
|
if (blank($slug)) {
|
|
continue;
|
|
}
|
|
|
|
$query = $this->model::query()
|
|
->where("{$this->column}->{$locale}", $slug);
|
|
|
|
if ($this->ignoreId !== null) {
|
|
$query->whereKeyNot($this->ignoreId);
|
|
}
|
|
|
|
// Soft-deleted rows still hold their slug, so include them —
|
|
// otherwise restoring one would resurrect a duplicate.
|
|
if (method_exists($this->model, 'bootSoftDeletes')) {
|
|
$query->withTrashed();
|
|
}
|
|
|
|
if ($query->exists()) {
|
|
$fail(__('rules.slug.unique', [
|
|
'slug' => $slug,
|
|
'locale' => (string) $locale,
|
|
]));
|
|
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|