Spatie handles translations with both database and language files primarily through its laravel-translation-loader package, which integrates seamlessly with Laravelâs native translation system.
How It Works When Using Both Database and Language Files
- The package allows you to store translations in the database using a dedicated table (`language_lines`). Each translation entry is represented by a `LanguageLine` model instance, which includes:
- `group`: The translation group (e.g., "validation" or "auth").
- `key`: The translation key within the group.
- `text`: An array holding translations for different locales (e.g., `['en' => 'This is a required field', 'nl' => 'Dit is een verplicht veld']`).
- When you request a translation using Laravelâs usual translation functions like `trans()` or `__()`, the package first checks the database for the translation. If it finds a matching entry, it returns the database version.
- If the translation is not found in the database, it falls back to the traditional language files stored in Laravelâs `resources/lang` directory.
- This means database translations override language file translations if both exist for the same key and locale.
- The package supports both group-based translations (e.g., `validation.required`) and JSON translations by using a special group name `'*'` for JSON translation lines.
Additional Features and Behavior
- The package caches groups of translations to optimize performance, reducing database queries on repeated translation requests. Cache is invalidated when translations are created, updated, or deleted.
- It is extendable: you can add custom translation providers (e.g., YAML, CSV) by implementing the packageâs `TranslationLoader` interface, allowing translations to be loaded from other sources beyond the database and language files.
- You can continue using Laravelâs default translation helpers and blade directives (`@lang`, `trans()`, `__()`) without modification.
Summary
Spatieâs translation loader package effectively merges database-stored translations with Laravelâs native file-based translations by prioritizing database entries. This allows dynamic editing of translations via a database-backed UI while retaining fallback to static language files. The integration is smooth, requiring minimal changes to existing translation calls, and offers caching and extensibility for advanced use cases[1][3][5][6][7].
Citations:
[1] https://github.com/spatie/laravel-translation-loader
[2] https://spatie.be/docs/laravel-translatable/v6/introduction
[3] https://laravel-news.com/translation-loader-package
[4] https://github.com/spatie/laravel-translatable
[5] https://www.laravelblogs.com/courses/multi-language-laravel/spatie-laravel-translation-loader
[6] https://packagist.org/packages/spatie/laravel-translation-loader
[7] https://freek.dev/593-a-laravel-package-to-store-language-lines-in-the-database
[8] https://laraveldaily.com/lesson/multi-language-laravel/spatie-laravel-translatable