Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

WBOY
Release: 2024-08-11 18:35:32
Original
566 people have browsed it

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
Copy after login

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

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

php artisan migrate
Copy after login

Step 4: Create the Translation Model

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

php artisan make:model Translation
Copy after login

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

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

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

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');
Copy after login

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
Copy after login

Displaying Translated Content in Views

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

{{ $post->title }}

{{ $post->content }}

Copy after login

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!

The above is the detailed content of Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!