DEV Community

Rafa Rafael
Rafa Rafael

Posted on

Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

When handling multilingual content, it’s often more efficient to store translations in a JSON column rather than individual rows for each attribute. This approach consolidates translations into a single column, simplifying data management and retrieval.

Setting Up the Translation System

We’ll enhance our Translation model and table to use a JSON column for storing translations. This will involve updating the table schema and modifying the Translatable trait to handle JSON data.

Step 1: Create Translations Table Migration

If the translations table does not already exist, create a new migration:

php artisan make:migration create_translations_table
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the Table Structure

Open the generated migration file in database/migrations. For a new table, define it as follows:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTranslationsTable extends Migration
{
    public function up()
    {
        Schema::create('translations', function (Blueprint $table) {
            $table->id();
            $table->string('locale'); // Stores the locale, e.g., 'en', 'fr'
            $table->string('translatable_type'); // Stores the related model type, e.g., 'Post', 'Product'
            $table->unsignedBigInteger('translatable_id'); // Stores the ID of the related model
            $table->json('translations'); // Stores all translations as a JSON object
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('translations');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the Migration
Apply the migration to your database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Translation Model

Next, create the Translation model to handle the polymorphic relationship:

php artisan make:model Translation
Enter fullscreen mode Exit fullscreen mode

In the Translation model, define the polymorphic relationship:

class Translation extends Model
{
    protected $fillable = ['locale', 'translatable_type', 'translatable_id', 'translations'];

    protected $casts = [
        'translations' => 'array',
    ];

    public function translatable()
    {
        return $this->morphTo();
    }
}
Enter fullscreen mode Exit fullscreen mode

Implementing the Translatable Trait with JSON Storage

To make translation handling reusable across multiple models, we’ll create a Translatable trait that will automatically load the translated content based on the user’s selected locale. Additionally, we’ll add a fallback mechanism to load content from the default locale if no translation is available for the selected locale.

Step 1: Create the Translatable Trait with JSON Handling

namespace App\Traits;

use App\Models\Translation;
use Illuminate\Support\Facades\App;

trait Translatable
{
    public static function bootTranslatable()
    {
        static::retrieved(function ($model) {
            $model->loadTranslations();
        });
    }

    public function translations()
    {
        return $this->morphMany(Translation::class, 'translatable');
    }

    public function loadTranslations()
    {
        $locale = App::getLocale();
        $defaultLocale = config('app.default_locale', 'en'); // Fallback to the default locale

        // Try to load translations for the current locale
        $translation = $this->translations()->where('locale', $locale)->first();

        if (!$translation && $locale !== $defaultLocale) {
            // If no translations are found for the current locale, fallback to the default locale
            $translation = $this->translations()->where('locale', $defaultLocale)->first();
        }

        if ($translation) {
            $translations = $translation->translations;
            foreach ($translations as $key => $value) {
                $this->{$key} = $value;
            }
        }
    }

    public function addTranslations(array $translations, $locale = null)
    {
        $locale = $locale ?? App::getLocale();
        return $this->translations()->updateOrCreate(
            ['locale' => $locale],
            ['translations' => $translations]
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Apply the Translatable Trait to Your Model
Add the Translatable trait to any model requiring translation support.

namespace App\Models;

use App\Traits\Translatable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Translatable;

    protected $fillable = ['title', 'content'];
}
Enter fullscreen mode Exit fullscreen mode

Example: Creating a Translated Model

Add translations as a JSON object:

$post = Post::create(['title' => 'Default Title', 'content' => 'Default Content']);

// Adding translations
$post->addTranslations([
    'title' => 'Hello World',
    'content' => 'Welcome to our website'
], 'en');

$post->addTranslations([
    'title' => 'Bonjour le monde',
    'content' => 'Bienvenue sur notre site Web'
], 'fr');
Enter fullscreen mode Exit fullscreen mode

Retrieving Translated Models

When you retrieve the Post model, it will automatically load the translated content based on the current locale or fall back to the default locale if necessary:

App::setLocale('fr');
$post = Post::find(1);
echo $post->title; // Displays "Bonjour le monde" if French translation exists

App::setLocale('es');
$post = Post::find(1);
echo $post->title; // Displays "Hello World" as it falls back to the English translation
Enter fullscreen mode Exit fullscreen mode

Displaying Translated Content in Views

In your Blade views, you can display the translated content like any other model attribute:

<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
Enter fullscreen mode Exit fullscreen mode

Conclusion

By using a JSON column to store translations and implementing a fallback mechanism, you streamline the management of multilingual content in your Laravel application. This approach consolidates translations into a single column, simplifying data handling and making your codebase more maintainable. Whether you’re building a blog, e-commerce site, or any multilingual application, this method ensures a smooth and efficient user experience.

Enjoy!

Top comments (0)