PHPackages                             indigoram89/laravel-translatable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. indigoram89/laravel-translatable

ActiveLibrary[Database &amp; ORM](/categories/database)

indigoram89/laravel-translatable
================================

A trait to make an Eloquent model hold translations

4.5.2(5y ago)0513MITPHP ^7.2

Since Apr 8Pushed 5y agoCompare

[ Source](https://github.com/indigoram89/laravel-translatable)[ Packagist](https://packagist.org/packages/indigoram89/laravel-translatable)[ Docs](https://github.com/spatie/laravel-translatable)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/indigoram89-laravel-translatable/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (5)Versions (47)Used By (3)

A trait to make Eloquent models translatable
============================================

[](#a-trait-to-make-eloquent-models-translatable)

[![Latest Version on Packagist](https://camo.githubusercontent.com/84243101d1a1e96438193f844bb47df7297d24f0a55c966c439a8c9c27d72ebd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d7472616e736c617461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-translatable)[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![GitHub Workflow Status](https://camo.githubusercontent.com/55481daf1d3bc73245f2e10105b103cc201ec15dba1fc5108037739a3cf362ad/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d7472616e736c617461626c652f72756e2d74657374733f6c6162656c3d7465737473)](https://camo.githubusercontent.com/55481daf1d3bc73245f2e10105b103cc201ec15dba1fc5108037739a3cf362ad/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d7472616e736c617461626c652f72756e2d74657374733f6c6162656c3d7465737473)[![Total Downloads](https://camo.githubusercontent.com/cf6bb0932610b395888b6e428a7355558aa08ac7d93a9533d4eff5f06509470b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d7472616e736c617461626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-translatable)

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
----------

[](#support-us)

[![](https://camo.githubusercontent.com/dc59c5caa4e0e03d95783ab3096e0e8922969e759f2e4cc017f11e5c825074b7/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d7472616e736c617461626c652e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-translatable)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#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
---------------------------

[](#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

[](#available-methods)

#### Getting a translation

[](#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

[](#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

[](#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

[](#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](https://github.com/codezero-be/laravel-unique-translation) which is made specifically for *laravel-translatable*.

#### Forgetting a translation

[](#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

[](#getting-all-translations-in-one-go)

```
public function getTranslations(string $attributeName): array
```

#### Setting translations in one go

[](#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

[](#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

[](#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

[](#events)

#### TranslationHasBeenSet

[](#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

[](#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

[](#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();
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Upgrading
---------

[](#upgrading)

### From v2 to v3

[](#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
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

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

Postcardware
------------

[](#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](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [All Contributors](../../contributors)

We got the idea to store translations as json in a column from [Mohamed Said](https://github.com/themsaid). Parts of the readme of [his multilingual package](https://github.com/themsaid/laravel-multilingual) were used in this readme.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community24

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 73.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~38 days

Recently: every ~5 days

Total

44

Last Release

2078d ago

Major Versions

0.0.1 → 1.0.02016-04-11

1.3.0 → 2.0.02017-08-30

2.2.1 → 3.0.02018-10-16

v3.x-dev → 4.0.02019-02-27

PHP version history (3 changes)0.0.1PHP ^7.0

3.0.0PHP ^7.1

4.1.0PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/b7a913b35ffe35ac2a30b0a3435a6e09a7b74184f74d265aa61e0ac45edaae35?d=identicon)[indigoram89](/maintainers/indigoram89)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (134 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (10 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (4 commits)")[![ctf0](https://avatars.githubusercontent.com/u/7388088?v=4)](https://github.com/ctf0 "ctf0 (2 commits)")[![alexjoffroy](https://avatars.githubusercontent.com/u/7209163?v=4)](https://github.com/alexjoffroy "alexjoffroy (2 commits)")[![ankurk91](https://avatars.githubusercontent.com/u/6111524?v=4)](https://github.com/ankurk91 "ankurk91 (2 commits)")[![ItsRD](https://avatars.githubusercontent.com/u/4502205?v=4)](https://github.com/ItsRD "ItsRD (2 commits)")[![YannikFirre](https://avatars.githubusercontent.com/u/3316758?v=4)](https://github.com/YannikFirre "YannikFirre (2 commits)")[![nateritter](https://avatars.githubusercontent.com/u/198798?v=4)](https://github.com/nateritter "nateritter (2 commits)")[![royduin](https://avatars.githubusercontent.com/u/1703233?v=4)](https://github.com/royduin "royduin (2 commits)")[![Propaganistas](https://avatars.githubusercontent.com/u/6680176?v=4)](https://github.com/Propaganistas "Propaganistas (1 commits)")[![robinmartini](https://avatars.githubusercontent.com/u/1028473?v=4)](https://github.com/robinmartini "robinmartini (1 commits)")[![RobLui](https://avatars.githubusercontent.com/u/10846766?v=4)](https://github.com/RobLui "RobLui (1 commits)")[![RonMelkhior](https://avatars.githubusercontent.com/u/1017721?v=4)](https://github.com/RonMelkhior "RonMelkhior (1 commits)")[![slovenianGooner](https://avatars.githubusercontent.com/u/1257629?v=4)](https://github.com/slovenianGooner "slovenianGooner (1 commits)")[![tdgroot](https://avatars.githubusercontent.com/u/1165302?v=4)](https://github.com/tdgroot "tdgroot (1 commits)")[![vguerrerobosch](https://avatars.githubusercontent.com/u/8974623?v=4)](https://github.com/vguerrerobosch "vguerrerobosch (1 commits)")[![vmitchell85](https://avatars.githubusercontent.com/u/1248035?v=4)](https://github.com/vmitchell85 "vmitchell85 (1 commits)")[![yaim](https://avatars.githubusercontent.com/u/2439084?v=4)](https://github.com/yaim "yaim (1 commits)")[![zehntinel](https://avatars.githubusercontent.com/u/7310519?v=4)](https://github.com/zehntinel "zehntinel (1 commits)")

---

Tags

spatietranslatemodeleloquentmultilinguallaravel-translatablei8n

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/indigoram89-laravel-translatable/health.svg)

```
[![Health](https://phpackages.com/badges/indigoram89-laravel-translatable/health.svg)](https://phpackages.com/packages/indigoram89-laravel-translatable)
```

###  Alternatives

[spatie/laravel-translatable

A trait to make an Eloquent model hold translations

2.5k25.2M506](/packages/spatie-laravel-translatable)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M91](/packages/mongodb-laravel-mongodb)[spatie/laravel-medialibrary

Associate files with Eloquent models

6.1k43.2M611](/packages/spatie-laravel-medialibrary)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k32.6M42](/packages/kirschbaum-development-eloquent-power-joins)[spatie/laravel-sluggable

Generate slugs when saving Eloquent models

1.6k12.9M295](/packages/spatie-laravel-sluggable)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M337](/packages/psalm-plugin-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
