new UniqueTranslation('posts', 'slug', 'tr', $post->id)
Created
September 25, 2025 10:07
-
-
Save afsakar/c5eb50788de178e7249d62533f814a50 to your computer and use it in GitHub Desktop.
A custom Laravel validation rule that checks for unique values in JSON translation columns. Supports both single locale validation and multi-locale array validation with optional record exclusion (useful for updates).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Rules; | |
| use Closure; | |
| use Illuminate\Contracts\Validation\ValidationRule; | |
| use Illuminate\Support\Facades\DB; | |
| use Illuminate\Translation\PotentiallyTranslatedString; | |
| class UniqueTranslation implements ValidationRule | |
| { | |
| public function __construct( | |
| protected string $table, | |
| protected string $column, | |
| protected ?string $locale = null, | |
| protected null | int | string $ignoreId = null | |
| ) { | |
| $this->locale = $locale ?: app()->getLocale(); | |
| } | |
| /** | |
| * Run the validation rule. | |
| * | |
| * @param Closure(string, ?string=): PotentiallyTranslatedString $fail | |
| */ | |
| public function validate(string $attribute, mixed $value, Closure $fail): void | |
| { | |
| if (is_array($value)) { | |
| foreach ($value as $locale => $translation) { | |
| if (empty($translation)) { | |
| continue; | |
| } | |
| $query = DB::table($this->table) | |
| ->whereRaw("JSON_EXTRACT({$this->column}, '$.{$locale}') = ?", [$translation]); | |
| if ($this->ignoreId) { | |
| $query->where('id', '!=', $this->ignoreId); | |
| } | |
| $localeLabel = locale_get_display_name($locale, $locale); | |
| if ($query->exists()) { | |
| $fail("Bu değer {$localeLabel} dilinde zaten kullanılmaktadır. Lütfen başka bir değer giriniz."); | |
| return; | |
| } | |
| } | |
| } else { | |
| if (empty($value)) { | |
| return; | |
| } | |
| $query = DB::table($this->table) | |
| ->whereRaw("JSON_EXTRACT({$this->column}, '$.{$this->locale}') = ?", [$value]); | |
| if ($this->ignoreId) { | |
| $query->where('id', '!=', $this->ignoreId); | |
| } | |
| $localeLabel = locale_get_display_name($this->locale, $this->locale); | |
| if ($query->exists()) { | |
| $fail("Bu değer {$localeLabel} dilinde zaten kullanılmaktadır. Lütfen başka bir değer giriniz."); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment