s-shiryaev / laravel-translatable
Trait for implementing model localization
Fund package maintenance!
s-shiryaev
Requires
- php: ^8.1
- illuminate/contracts: ^10.0
- illuminate/database: ^10.0
- illuminate/support: ^10.0
Requires (Dev)
- brianium/paratest: ^7.0
- nunomaduro/collision: ^7.9
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^8.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^10
README
This package contains a trait to make it easier to work with translating Eloquent models.
Installation
You can install the package via composer:
composer require s-shiryaev/laravel-translatable
Version Compatibility
Usage
Just add the SShiryaev\LaravelTranslatable\Translatable
trait to the model and create a property translatable
, which holds an array with all the names of attributes you wish to make translatable:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use SShiryaev\LaravelTranslatable\Translatable; class Currency extends Model { use Translatable; protected $translatable = ['name', 'code']; protected $fillable = [ 'id', 'name_ru', 'name_en', 'code_ru', 'code_en', 'code_de', 'active', 'sort', ]; }
Now, when accessing the properties of the model, the value will be returned in accordance with the application locale:
App::setLocale('ru'); $currency = new Currency(['name_ru' => 'Доллар', 'name_en' => 'Dollar']); echo $currency->name; //Доллар
Also, when converting a model and their eloquent collection to an array (for example, in presenters), field values will be returned according to the application locale:
App::setLocale('ru'); $currency = Currency::find(1); $currency->toArray(); //['name' => 'Доллар', 'name_en' => 'Dollar'] $currencies = Currency::all(); $currencies->toArray(); //[0 => ['name' => 'Доллар', 'name_en' => 'Dollar']]
Sometimes, when converting to an array, you need to get the original fields of the model without translation. This can be done by passing an optional parameter in the toArray()
method:
$currency = Currency::find(1); $currency->toArray(false); //['name_ru' => 'Доллар', 'name_en' => 'Dollar'] $currencies = Currency::all(); $currencies->toArray(false); //[0 => ['name_ru' => 'Доллар', 'name_en' => 'Dollar']]
Translation also works with relationships.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.