Preparing your model

To enable the translation feature in a model, the model must implement the TranslatableModel interface and use the Translatable trait. The model also needs to declare $translates as protected property which contains a list of translatable attribute names.

app/Models/Product.php
use Illuminate\Database\Eloquent\Model;
use RichanFongdasen\I18n\Contracts\TranslatableModel;
use RichanFongdasen\I18n\Eloquent\Concerns\Translatable;

class Product extends Model implements TranslatableModel
{
    use Translatable;
    
    /**
     * It is required to define all 
     * the translatable attribute names here.
     *
     * @var string[]
     */
    protected array $translates = [
        'description',
        'details'
    ];
}

Customize the translation table name

The package will be able to guess the translation table name as product_translations by default. But you can customize the translation table name by declaring a protected property in your model.

class Product extends Model implements TranslatableModel
{
    use Translatable;

    /**
     * The database table name to store the translation data.
     *
     * @var string
     */
    protected string $translationTable = 'custom_product_translations';
}

Hide the translations attribute

The package will load the translations relationship in every eloquent query via eager loading. If you're working with an API application, it is recommended to hide the translations relationship that contains all the translation models.

class Product extends Model implements TranslatableModel
{
    use Translatable;

    /**
     * Hides the translations attribute, so it won't present
     * when the model is serialized into an array or JSON document.
     * @var string[]
     */
    protected $hidden = ['translations'];
}

Define the translation accessor

Defining an accessor for each translatable attribute will become handy, especially when you're working with an API application. With the help of accessors, you can append or remove the translatable attributes with ease in the future.

class Product extends Model implements TranslatableModel
{
    use Translatable;

    /**
     * Get the translated `description` attribute.
     *
     * @return string
     * @throws \ErrorException
     */
    public function getDescriptionAttribute(): string
    {
        return (string) $this->getAttribute('description');
    }

    /**
     * Get the translated `details` attribute.
     *
     * @return string
     * @throws \ErrorException
     */
    public function getDetailsAttribute(): string
    {
        return (string) $this->getAttribute('details');
    }
}
Edit this page on GitHub Updated at Wed, May 25, 2022