DEV Community

Cover image for Simplifying Multilingual Models in Laravel with Lexi Translate
Omar Alalwi
Omar Alalwi

Posted on

Simplifying Multilingual Models in Laravel with Lexi Translate

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
Enter fullscreen mode Exit fullscreen mode

Publish the Configuration File

Run the following command to publish the configuration file:

php artisan vendor:publish --tag=lexi-translate
Enter fullscreen mode Exit fullscreen mode

Migration for the Translations Table

Create the required database tables for translations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

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'];
}
Enter fullscreen mode Exit fullscreen mode

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',
    ],
]);
Enter fullscreen mode Exit fullscreen mode
Single Translation

Alternatively, use setTranslation to update a single field:

$post->setTranslation('title', 'en', 'English Title');
$post->setTranslation('description', 'ar', 'وصف باللغة العربية');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
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!');
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Features

  1. Dynamic Morph Relationships: Manage translations across different models with ease.
  2. Automatic Caching: Improves performance by caching translations and automatically clearing them when updated.
  3. Fallback Mechanism: Falls back to the default language if a translation is missing.
  4. Intuitive API: Simple methods for adding, retrieving, and managing translations.
  5. Customizable Configurations: Change table names and locales in the configuration file.
  6. 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:

  1. Relational Storage: Uses a dedicated translations table with dynamic morph relationships for scalability.
  2. Built-in Caching: Ensures fast retrieval and automatic cache invalidation.
  3. Dynamic API: Provides bulk translation methods and flexible configurations.
  4. 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)