Querying Translations - nevadskiy/laravel-translatable GitHub Wiki

To perform database queries using translatable attributes, each strategy provides a set of query scopes.

whereTranslatable

You can execute where queries on translatable models using the whereTranslatable scope:

$book = Book::whereTranslatable('title', 'Тіні незабутих предків')->first();

This query will search for books by the translatable title attribute according to the given value among translations for all locales.

To specify a specific locale to search for, it can be passed as the third argument:

$book = Book::whereTranslatable('title', 'Тіні незабутих предків', 'uk')->first();

Also, you can use different operators for querying translatable records by passing it as the fourth argument:

$books = Book::whereTranslatable('title', 'Тіні незабутих%', null, 'LIKE')->get();

The or scope is also available:

$books = Book::query()
    ->whereTranslatable('title', 'Тіні незабутих предків', 'uk')
    ->orWhereTranslatable('title', 'Shadow unforgotten ancestors', 'en')
    ->get();

For more complex queries feel free to use custom Laravel Relation Queries.

orderByTranslatable

To sort models by translatable attribute, you can use the orderByTranslatable scope:

$books = Book::orderByTranslatable('title')->get();

This method will sort the models by the current translator locale.

You can also sort models by custom locale:

$books = Book::orderByTranslatable('title', 'desc', 'uk')->get();

Eager loading

Since translations are stored in separate tables, to avoid the "N + 1" query problem, when querying translatable models, they will eager load translations for the current and fallback locales using the Nevadskiy\Translatable\Scopes\TranslationsEagerLoadingScope global scope.

$this->app->setLocale('uk'); // Assume the "en" locale is a fallback locale.

$books = Book::get(); // Translations to 'en' and 'uk' locales are eager loaded. 

Also, you can disable this global scope using the withoutTranslationsScope scope:

$books = Book::withoutTranslationsScope()->get(); // No translations eager loaded.

Although the translations will not be eager loaded, the translator can load them lazily when interacting with the translations.

You can also manually eager load translations to the desired locales:

$books = Book::withTranslations()->get(); // Translations to all locales are loaded.  
$books = Book::withTranslations(['en', 'uk'])->get(); // Translations to 'en' and 'uk' locales are loaded.