Created
October 25, 2024 13:37
-
-
Save A909M/204d8ed92cffc44ed66bfa36ef935cb4 to your computer and use it in GitHub Desktop.
This trait provides a search scope for models with JSON fields containing Arabic text, adding support for common Arabic character variations (like 'ه' vs. 'ة') to improve search accuracy. Usage:
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\Traits; | |
| use Illuminate\Database\Eloquent\Builder; | |
| trait SearchTranslatableField | |
| { | |
| public function scopeSearchByTranslatableField(Builder $query, string $value, string $field = 'name'): Builder | |
| { | |
| $normalizedPattern = $this->normalizeArabic($value); | |
| return $query->where(function (Builder $query) use ($value, $normalizedPattern, $field) { | |
| $query->whereRaw('LOWER(' . $field . '->"$.en") LIKE ?', ['%' . strtolower($value) . '%']) | |
| ->orWhereRaw($field . '->"$.ar" REGEXP ?', [$normalizedPattern]); | |
| }); | |
| } | |
| protected function normalizeArabic(string $value): string | |
| { | |
| $replacements = [ | |
| 'ه' => '[هة]', | |
| 'ة' => '[هة]', | |
| 'ا' => '[اأإ]', | |
| 'أ' => '[اأإ]', | |
| 'إ' => '[اأإ]', | |
| ]; | |
| $pattern = ''; | |
| $length = mb_strlen($value, 'UTF-8'); | |
| for ($i = 0; $i < $length; $i++) { | |
| $char = mb_substr($value, $i, 1, 'UTF-8'); | |
| if (isset($replacements[$char])) { | |
| $pattern .= $replacements[$char]; | |
| } else { | |
| $escapedChar = preg_quote($char, '/'); | |
| $pattern .= $escapedChar; | |
| } | |
| } | |
| return $pattern; | |
| } | |
| public function scopeName(Builder $query, string $value): Builder | |
| { | |
| return $query->searchByTranslatableField($value, "{$this->getTable()}.name"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment