"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

Published on 2024-08-18
Browse:217

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

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');
    }
}

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

php artisan migrate

Step 4: Create the Translation Model

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

php artisan make:model Translation

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();
    }
}

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]
        );
    }
}

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'];
}

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');

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

Displaying Translated Content in Views

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

{{ $post->title }}

{{ $post->content }}

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!

Release Statement This article is reproduced at: https://dev.to/rafaelogic/building-a-polymorphic-translatable-model-in-laravel-with-autoloaded-translations-3d99?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3