2017 © Pedro PelĂĄez
 

library laravel-translatable

Translatable models for Laravel 5

image

indigoram89/laravel-translatable

Translatable models for Laravel 5

  • Tuesday, February 21, 2017
  • by indigoram89
  • Repository
  • 1 Watchers
  • 0 Stars
  • 6 Installations
  • PHP
  • 3 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

A trait to make Eloquent models translatable

Latest Version on Packagist MIT Licensed GitHub Workflow Status Total Downloads, (*1)

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

Once the trait is installed on the model you can do these things:, (*3)

$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

, (*4)

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., (*5)

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., (*6)

Installation

You can install the package via composer:, (*7)

``` bash composer require spatie/laravel-translatable, (*8)


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", (*9)


This is the contents of the published file: ```php return [ 'fallback_locale' => 'en', ];

Making a model translatable

The required steps to make a model translatable are:, (*10)

  • 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:, (*11)

``` php use Illuminate\Database\Eloquent\Model; use Spatie\Translatable\HasTranslations;, (*12)

class NewsItem extends Model { use HasTranslations;, (*13)

public $translatable = ['name'];

}, (*14)


### 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): ```php $newsItem->name;

You can also use this method:, (*15)

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

This function has an alias named translate., (*16)

Getting all translations

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

$newsItem->getTranslations();

Or you can use the accessor, (*18)

$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):, (*19)

$newsItem->name = 'New translation';

Also you can set translations with, (*20)

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

To set a translation for a specific locale you can use this method:, (*21)

``` php public function setTranslation(string $attributeName, string $locale, string $value), (*22)


To actually save the translation, don't forget to save your model. ```php $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: ``` php public function forgetTranslation(string $attributeName, string $locale), (*23)


You can forget all translations for a specific locale: ``` php public function forgetAllTranslations(string $locale)

Getting all translations in one go

``` php public function getTranslations(string $attributeName): array, (*24)


#### Setting translations in one go ``` php public function setTranslations(string $attributeName, array $translations)

Here's an example:, (*25)

``` php $translations = [ 'en' => 'Name in English', 'nl' => 'Naam in het Nederlands' ];, (*26)

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


#### Replace translations in one go You can replace all the translations for a single key using this method: ```php public function replaceTranslations(string $key, array $translations)

Here's an example:, (*28)

$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., (*29)

To do so, you can use setLocale on a model instance. ``` php $newsItem = NewsItem::firstOrFail()->setLocale('fr');, (*30)

// 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, (*31)


Alternatively, you can use `usingLocale` static method: ``` php // 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., (*32)

It has these properties:, (*33)

/** @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:, (*34)

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:, (*35)

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

Or if you're using MariaDB 10.2.3 or above :, (*36)

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

Changelog

Please see CHANGELOG for more information what has changed recently., (*37)

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., (*38)

Testing

composer test

Contributing

Please see CONTRIBUTING for details., (*39)

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker., (*40)

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., (*41)

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium., (*42)

We publish all received postcards on our company website., (*43)

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., (*44)

License

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

The Versions

21/02 2017

dev-master

9999999-dev https://github.com/indigoram89/laravel-translatable

Translatable models for Laravel 5

  Sources   Download

MIT

The Requires

 

The Development Requires

by Max Orlov

laravel translatable indigoram89

21/02 2017

1.0.0

1.0.0.0 https://github.com/indigoram89/laravel-translatable

Translatable models for Laravel 5

  Sources   Download

MIT

The Requires

 

The Development Requires

by Max Orlov

laravel translatable indigoram89