Making Eloquent models translatable

Overview

A trait to make Eloquent models translatable

Latest Version on Packagist MIT Licensed GitHub Workflow Status Total Downloads

This package contains a trait to make Eloquent models translatable. Translations are stored as json. There is no extra table needed to hold them.

Once the trait is installed on the model you can do these things:

$newsItem = new NewsItem; // This is an Eloquent model
$newsItem
   ->setTranslation('name', 'en', 'Name in English')
   ->setTranslation('name', 'nl', 'Naam in het Nederlands')
   ->save();
   
$newsItem->name; // Returns 'Name in English' given that the current app locale is 'en'
$newsItem->getTranslation('name', 'nl'); // returns 'Naam in het Nederlands'

app()->setLocale('nl');

$newsItem->name; // Returns 'Naam in het Nederlands'

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-translatable

If you want to have another fallback_locale than the app fallback locale (see config/app.php), you could publish the config file:

php artisan vendor:publish --provider="Spatie\Translatable\TranslatableServiceProvider"

This is the contents of the published file:

return [
  'fallback_locale' => 'en',
];

Making a model translatable

The required steps to make a model translatable are:

  • First, you need to add the Spatie\Translatable\HasTranslations-trait.
  • Next, you should create a public property $translatable which holds an array with all the names of attributes you wish to make translatable.
  • Finally, you should make sure that all translatable attributes are set to the text-datatype in your database. If your database supports json-columns, use that.

Here's an example of a prepared model:

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class NewsItem extends Model
{
    use HasTranslations;
    
    public $translatable = ['name'];
}

Available methods

Getting a translation

The easiest way to get a translation for the current locale is to just get the property for the translated attribute. For example (given that name is a translatable attribute):

$newsItem->name;

You can also use this method:

public function getTranslation(string $attributeName, string $locale, bool $useFallbackLocale = true) : string

This function has an alias named translate.

Getting all translations

You can get all translations by calling getTranslations() without an argument:

$newsItem->getTranslations();

Or you can use the accessor

$yourModel->translations

Setting a translation

The easiest way to set a translation for the current locale is to just set the property for a translatable attribute. For example (given that name is a translatable attribute):

$newsItem->name = 'New translation';

Also you can set translations with

$newItem->name = ['en' => 'myName', 'nl' => 'Naam in het Nederlands'];

To set a translation for a specific locale you can use this method:

public function setTranslation(string $attributeName, string $locale, string $value)

To actually save the translation, don't forget to save your model.

$newsItem->setTranslation('name', 'en', 'Updated name in English');

$newsItem->save();

Validation

  • if you want to validate an attribute for uniqueness before saving/updating the db, you might want to have a look at laravel-unique-translation which is made specifically for laravel-translatable.

Forgetting a translation

You can forget a translation for a specific field:

public function forgetTranslation(string $attributeName, string $locale)

You can forget all translations for a specific locale:

public function forgetAllTranslations(string $locale)

Getting all translations in one go

public function getTranslations(string $attributeName): array

Setting translations in one go

public function setTranslations(string $attributeName, array $translations)

Here's an example:

$translations = [
   'en' => 'Name in English',
   'nl' => 'Naam in het Nederlands'
];

$newsItem->setTranslations('name', $translations);

Replace translations in one go

You can replace all the translations for a single key using this method:

public function replaceTranslations(string $key, array $translations)

Here's an example:

$translations = ['en' => 'hello', 'es' => 'hola'];

$newsItem->setTranslations('hello', $translations);
$newsItem->getTranslations(); // ['en' => 'hello', 'es' => 'hola']

$newTranslations = ['en' => 'hello'];

$newsItem->replaceTranslations('hello', $newTranslations);
$newsItem->getTranslations(); // ['en' => 'hello']

Setting the model locale

The default locale used to translate models is the application locale, however it can sometimes be handy to use a custom locale.

To do so, you can use setLocale on a model instance.

$newsItem = NewsItem::firstOrFail()->setLocale('fr');

// Any properties on this model will automaticly be translated in French
$newsItem->name; // Will return `fr` translation
$newsItem->name = 'Actualité'; // Will set the `fr` translation

Alternatively, you can use usingLocale static method:

// Will automatically set the `fr` translation
$newsItem = NewsItem::usingLocale('fr')->create([
    'name' => 'Actualité',
]);

Events

TranslationHasBeenSet

Right after calling setTranslation the Spatie\Translatable\Events\TranslationHasBeenSet-event will be fired.

It has these properties:

/** @var \Illuminate\Database\Eloquent\Model */
public $model;

/** @var string  */
public $attributeName;

/** @var string  */
public $locale;

public $oldValue;
public $newValue;

Creating models

You can immediately set translations when creating a model. Here's an example:

NewsItem::create([
   'name' => [
      'en' => 'Name in English',
      'nl' => 'Naam in het Nederlands'
   ],
]);

Querying translatable attributes

If you're using MySQL 5.7 or above, it's recommended that you use the json data type for housing translations in the db. This will allow you to query these columns like this:

NewsItem::where('name->en', 'Name in English')->get();

Or if you're using MariaDB 10.2.3 or above :

NewsItem::whereRaw("JSON_EXTRACT(name, '$.en') = 'Name in English'")->get();

Automatically display the right translation when displaying model

Many times models using HasTranslation trait may be directly returned as response content. In this scenario, and similar ones, the toArray() method on Model class is called under the hood to serialize your model; it accesses directly the $attributes field to perform the serialization, bypassing the translatable feature (which is based on accessors and mutators) and returning the text representation of the stored JSON instead of the translated value.

The best way to make your model automatically return translated fields is to wrap Spatie\Translatable\HasTranslations trait into a custom trait which overrides the toArray() method to automatically replace all translatable fields content with their translated value, like in the following example, and use it instead of the default one.

namespace App\Traits;
use Spatie\Translatable\HasTranslations as BaseHasTranslations;
trait HasTranslations
{
    use BaseHasTranslations;
    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function toArray()
    {
        $attributes = parent::toArray();
        foreach ($this->getTranslatableAttributes() as $field) {
            $attributes[$field] = $this->getTranslation($field, \App::getLocale());
        }
        return $attributes;
    }
}

Changelog

Please see CHANGELOG for more information what has changed recently.

Upgrading

From v2 to v3

In most cases you can upgrade without making any changes to your codebase at all. v3 introduced a translations accessor on your models. If you already had one defined on your model, you'll need to rename it.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

We got the idea to store translations as json in a column from Mohamed Said. Parts of the readme of his multilingual package were used in this readme.

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Fix: Remove the provider

    Fix: Remove the provider

    The provider is no longer required.

    Laravel 5.8 is throwing errors while installing this (v4.1) package -

    Generating optimized autoload files
    > Illuminate\Foundation\ComposerScripts::postAutoloadDump
    > @php artisan package:discover --ansi
    
    In ProviderRepository.php line 208:
                                                                         
      Class 'Spatie\Translatable\TranslatableServiceProvider' not found  
                                                                         
    
    Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
    
    opened by ankurk91 9
  • Support Laravel 9 attribute cast accessor/mutator

    Support Laravel 9 attribute cast accessor/mutator

    Laravel 9 added a new way to add Accessors/Mutators to models which uses a Attribute class to handle the transformation of values.

    Old:

    public function setFieldWithMutatorAttribute($value)
    {
        $this->attributes['field_with_mutator'] = $value;
    }
    

    New:

    use Illuminate\Database\Eloquent\Casts\Attribute;
    
    protected function fieldWithMutator(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => $value,
        );
    }
    

    The old way is still supported but there is no mention of it in the Laravel 9 documentation, I added tests to support the new Attribute class and now both versions are supported.

    opened by remul 7
  • Allow translation of

    Allow translation of "array" fields

    This is an attempt to allow translations for arrays. To make this work, two things were necessary:

    1. Remove the return type hint of string from the getTranslation() method
    2. Refactor the is_array() check in setAttribute() that defers to parent::setAttribute() when the value is an array

    In consequence of 2) it would become impossible to set all translations directly by setting the value of an attribute to an array. Therefore i've introduced a check against the models' casts property to only pass through to parent::setAttribute() if the attribute is not declared as "cast to array".

    This should preserve all previous behaviour with basic strings. It only introduces the limitation that one has to use setTranslations() in order to set all translation of an array cast attribute.

    opened by jsphpl 6
  • Filter empty/null translations

    Filter empty/null translations

    Why I think this should be merged:

    I've a form with 4 input fields:

    <input type="text" name="name[nl]">
    <input type="text" name="name[en]">
    <input type="text" name="name[de]">
    <input type="text" name="name[fr]">
    

    When I submit the form and won't fill the English translation it will be saved like this in the DB:

    {"de": "DE", "en": null, "fr": "FR", "nl": "NL"}
    

    So when I change the locale to English I'm not getting anything because it's null. It should fallback to the fallback locale (in my case NL) because I've set so.

    In this PR I'm filtering out those empty translations so the fallback is working.

    opened by royduin 6
  • add setAttribute for stright storing values for translatable attribute

    add setAttribute for stright storing values for translatable attribute

    Sometimes need to use attribute assignment without known translations, ex. at model mass assignment very uncomfortable provide whole structure of translation object.

    I try to patch Model::setAttribute method to overcome this issue

    opened by Astyk 6
  • Add support for storing unescaped Unicode in DB

    Add support for storing unescaped Unicode in DB

    This is a fix for #134

    It defaults to the original behavior, so existing code shouldn't break or be affected at all. This PR simply adds an option to workaround the issue.

    This is important for searching through Unicode characters using LIKE query.

    opened by MicroDroid 5
  • fix: allow JSON fields to be translated

    fix: allow JSON fields to be translated

    Currently, it is not possible to translate JSON fields because the is_array condition becomes true when you pass an array (i.e. a decoded JSON object). This PR adds a simple check that checks if the passed object is an array with locale keys only and if the condition is true it sets all translations at once.

    opened by jaulz 4
  • Make isTranslatableAttribute() public

    Make isTranslatableAttribute() public

    I stumbled upon the case where I need to check if an attribute is translatable, e.g.:

    $attribute = 'name'; // Defined elsewhere dynamically.
    
    if ($model->isTranslatableAttribute($attribute)) {
       // Do something here...
    }
    

    I can do the check manually using getTranslatedAttributes() but in the end I'd just have a copy of isTranslatableAttribute()... So let's expose it..

    opened by Propaganistas 4
  • Handle attribute set in all scenarios

    Handle attribute set in all scenarios

    This will save a translatable attribute in the right way.

    Case 1: The attribute value is a string

    Will be se a translation for the current locale.

    Case 2: The attribute value is an array

    Is already in the right form.

    Case 3: JSON encoded string

    Will be decoded and the translations will be set.

    opened by f-liva 4
  • Added whereLocale and whereLocales methods

    Added whereLocale and whereLocales methods

    In some cases, there are times when I want to extract content according to the user's locale, and in this case, I found these solutions instead of constantly writing queries.

    whereLocale and whereLocales methods.

    $post->whereLocale('title', 'en')->get();
    
    // or mutliple locales
    $post->whereLocales('title', ['en', 'fr'])->get();
    
    opened by ahmetbarut 3
  • PHPUnit to Pest Converter

    PHPUnit to Pest Converter

    This pull request contains changes for migrating your test suite from PHPUnit to Pest automated by the Pest Converter.

    Before merging, you need to:

    • Checkout the shift-57946 branch
    • Review all of the comments below for additional changes
    • Run composer update to install Pest with your dependencies
    • Run vendor/bin/pest to verify the conversion
    opened by freekmurze 3
Releases(6.2.0)
Owner
Spatie
Webdesign agency based in Antwerp, Belgium
Spatie
[Deprecated] A Laravel package for multilingual models

This package has been deprecated. But worry not. You can use Astrotomic/laravel-translatable. Laravel-Translatable If you want to store translations o

Dimitris Savvopoulos 2k Dec 25, 2022
Making multiple identical function calls has the same effect as making a single function call.

Making multiple identical function calls has the same effect as making a single function call.

李铭昕 4 Oct 16, 2021
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

Maarten Tolhuijs 1.4k Dec 31, 2022
Doctrine2 behavioral extensions, Translatable, Sluggable, Tree-NestedSet, Timestampable, Loggable, Sortable

Doctrine Behavioral Extensions This package contains extensions for Doctrine ORM and MongoDB ODM that offer new functionality or tools to use Doctrine

Doctrine Extensions 3.8k Jan 5, 2023
Doctrine2 behavioral extensions, Translatable, Sluggable, Tree-NestedSet, Timestampable, Loggable, Sortable

Doctrine Behavioral Extensions This package contains extensions for Doctrine ORM and MongoDB ODM that offer new functionality or tools to use Doctrine

Doctrine Extensions 3.8k Jan 5, 2023
Extracts translatable strings from source. Identical to xgettext but for template languages.

xgettext-template Extracts translatable strings from source. Identical to xgettext(1) but for template languages. Template language support Handlebars

Guillaume C. Marty 79 Oct 7, 2022
This module integrates Silverstripe CMS with Google Translate API and then allows content editors to use automatic translation for every translatable field.

Autotranslate This module integrates Silverstripe CMS with Google Translate API and then allows content editors to use automatic translation for every

null 4 Jan 3, 2022
⚡️ Models like Eloquent for Elasticsearch.

Elasticsearch Eloquent 2.x This package allows you to interact with Elasticsearch as you interact with Eloquent models in Laravel. Requirements PHP >=

Sergey Sorokin 111 Dec 19, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
Sortable behaviour for Eloquent models

Sortable behaviour for Eloquent models This package provides a trait that adds sortable behaviour to an Eloquent model. The value of the order column

Spatie 1.2k Dec 22, 2022
This package gives Eloquent models the ability to manage their friendships.

Laravel 5 Friendships This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Alex Kyriakidis 690 Nov 27, 2022
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 955 Dec 25, 2022
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 879 Dec 30, 2022
cybercog 996 Dec 28, 2022
Maps Laravel Eloquent models to Elasticsearch types

Elasticquent Elasticsearch for Eloquent Laravel Models Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Ela

Elasticquent 1.3k Jan 4, 2023
Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a fluent syntax for mapping, querying, and storing eloquent models.

Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a f

Sleiman Sleiman 511 Dec 31, 2022
Laravel Scout provides a driver based solution to searching your Eloquent models.

Introduction Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. Once Scout is installed and c

The Laravel Framework 1.3k Dec 31, 2022
Create presenters for Eloquent Models

Laravel Presentable This package allows the information to be presented in a different way by means of methods that can be defined in the model's pres

The Hive Team 67 Dec 7, 2022