Simplifying Multilingual Models in Laravel with Lexi Translate
Managing multilingual content in Laravel applications can often become cumbersome, especially when dealing with complex models and performance concerns. Enter Lexi Translate – a lightweight and powerful package designed to simplify managing translations for multilingual Eloquent models.
In this article, we’ll explore the features, setup, and usage of Lexi Translate, showcasing how it can help developers efficiently handle translations with caching, morph relationships, and more.
What is Lexi Translate?
Lexi Translate is a Laravel package that brings elegance and simplicity to managing translations for Eloquent models. It uses dynamic morph relationships to link translations, leverages caching for performance, and integrates seamlessly with Laravel's ORM.
Installing and Setting Up Lexi Translate
To get started, install Lexi Translate via Composer:
composer require omaralalwi/lexi-translate
Publish the Configuration File
Run the following command to publish the configuration file:
php artisan vendor:publish --tag=lexi-translate
Migration for the Translations Table
Create the required database tables for translations:
php artisan migrate
Getting Started with Lexi Translate
Defining LexiTranslatable Models
To use the package, include the LexiTranslatable
trait in your Eloquent models and define translatable attributes in the $translatableFields
array:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Omaralalwi\LexiTranslate\Traits\LexiTranslatable;
class Post extends Model
{
use LexiTranslatable;
protected $translatableFields = ['title', 'description'];
}
Updating or Creating Translations
Bulk Translations
You can use the setTranslations
method to add or update multiple translations at once:
$post = Post::find(1);
$post->setTranslations([
'ar' => [
'title' => 'العنوان باللغة العربية',
'description' => 'الوصف باللغة العربية',
],
'en' => [
'title' => 'English Title',
'description' => 'Description in English',
],
]);
Single Translation
Alternatively, use setTranslation
to update a single field:
$post->setTranslation('title', 'en', 'English Title');
$post->setTranslation('description', 'ar', 'وصف باللغة العربية');
Note: Translatable attributes don’t need to exist in the parent model’s schema.
Retrieving Translations
To fetch translations, use the transAttr
method:
// Get title in the default app locale
$title = $post->transAttr('title');
// Get title in a specific locale
$titleInArabic = $post->transAttr('title', 'ar');
Frontend and Backend Integration
Blade Example:
<form action="{{ route('translations.store', $post->id) }}" method="POST">
@csrf
@foreach (lexi_locales() as $locale)
<h4>{{ strtoupper($locale) }}</h4>
@foreach ($post->getTranslatableFields() as $field)
<div>
<label for="{{ $field }}_{{ $locale }}">{{ ucfirst($field) }} ({{ $locale }})</label>
<input type="text" name="translations[{{ $locale }}][{{ $field }}]"
value="{{ $post->transAttr($field, $locale) }}" />
</div>
@endforeach
@endforeach
<button type="submit">Save Translations</button>
</form>
Controller Example:
use Illuminate\Http\Request;
use App\Models\Service;
class TranslationsController extends Controller
{
public function store(Request $request, $id)
{
$translations = $request->input('translations');
$service = Service::findOrFail($id);
$service->setTranslations($translations);
return redirect()->back()->with('success', 'Translations updated successfully!');
}
}
Key Features
- Dynamic Morph Relationships: Manage translations across different models with ease.
- Automatic Caching: Improves performance by caching translations and automatically clearing them when updated.
- Fallback Mechanism: Falls back to the default language if a translation is missing.
- Intuitive API: Simple methods for adding, retrieving, and managing translations.
- Customizable Configurations: Change table names and locales in the configuration file.
- Built-in middlewares to handle locale switching seamlessly for both web and API requests.
Comparing Lexi Translate with Spatie and Astrotomic
While Spatie Laravel Translatable and Astrotomic Laravel Translatable are popular alternatives, Lexi Translate offers unique advantages:
- Relational Storage: Uses a dedicated translations table with dynamic morph relationships for scalability.
- Built-in Caching: Ensures fast retrieval and automatic cache invalidation.
- Dynamic API: Provides bulk translation methods and flexible configurations.
- Support for Large Applications: Excels in handling extensive multilingual content compared to JSON-based approaches.
When to Choose Lexi Translate
Lexi Translate is ideal for:
- Applications managing large volumes of translations.
- Scenarios requiring high performance and caching.
- Projects needing translations for attributes outside the parent model's schema.
For smaller applications or simpler use cases, Spatie or Astrotomic may suffice.
Conclusion
Lexi Translate simplifies multilingual content management in Laravel. Its dynamic relationships, robust caching, and scalability make it a top choice for developers building high-performance, multilingual applications. If JSON-based solutions feel limiting, Lexi Translate offers the flexibility and power you need.
Ready to get started? Install Lexi Translate today and elevate your multilingual applications!
Top comments (0)