The mindtwo/laravel-translatable
package provides a simple and effective way to manage multilingual models in a Laravel application. It allows you to easily translate Eloquent model attributes into multiple languages without the need for separate tables for each language.
- Easy integration with Eloquent models.
- Seamless translation of model attributes.
- Simple configuration and usage.
To install the package, run the following command in your Laravel project:
composer require mindtwo/laravel-translatable
You can publish and run the migrations with:
php artisan vendor:publish --tag="translatable-migrations"
php artisan migrate
You can publish the config file with:
php artisan vendor:publish --tag="translatable-config"
This is the contents of the published config file:
<?php
use mindtwo\LaravelTranslatable\Models\Translatable;
return [
'model' => Translatable::class,
];
After installation, you need to publish and run the migrations:
php artisan vendor:publish --provider="mindtwo\LaravelTranslatable\TranslatableServiceProvider"
php artisan migrate
This will create a translatable
table in your database.
-
Migration: Use the provided
create_translatable_table.php
migration to set up thetranslatable
table. -
Model Trait: Include the
HasTranslations
trait in your model. This trait provides methods to interact with translations.use mindtwo\LaravelTranslatable\Traits\HasTranslations; class YourModel extends Model { use HasTranslations; // Model content }
-
Translatable Model: The
Translatable
model is used to store translations. It uses theAutoCreateUuid
trait for unique identification.use mindtwo\LaravelTranslatable\Models\Translatable; // Usage within your application logic
-
Add a Translation:
$yourModelInstance->translations()->create([ 'key' => 'your_key', 'locale' => 'en', 'text' => 'Your translation text' ]);
-
Check for a Translation:
$exists = $yourModelInstance->hasTranslation('your_key', 'en');
-
Get a Translation:
$translation = $yourModelInstance->getTranslation('your_key', 'en');
-
Retrieve All Translations:
$translations = $yourModelInstance->getTranslations();
- Always check if a translation exists before attempting to retrieve it.
- Use consistent keys across different models to maintain clarity.
- Regularly back up your translations as they are stored in the database.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.