Home Backend Development PHP Tutorial Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

Building a Polymorphic Translatable Model in Laravel with Autoloaded Translations

Aug 11, 2024 pm 06:35 PM

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:

<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles