astrotomic/laravel-translatable
Laravel package for translatable Eloquent models. Store model translations in the database and automatically fetch/save multilingual attributes based on locale, reducing boilerplate when working with multi-language content.
Examples for all the package features can be found in the code used for the tests.
Got any question or suggestion? Feel free to open an Issue.
You are awesome! Watch the repo and reply to the issues. You will help offering a great experience to the users of the package. #communityWorks
Translatable is fully compatible with all kinds of Eloquent extensions, including Ardent. If you need help to implement Translatable with these extensions, see this example.
Please see the installation steps to understand how your database should be structured.
If your properties are written in english, we recommend using these commands in your migrations:
// We insert the old attributes into the fresh translation table:
\DB::statement("insert into country_translations (country_id, name, locale) select id, name, 'en' from countries");
// We drop the translation attributes in our main table:
Schema::table('posts', function ($table) {
$table->dropColumn('title');
$table->dropColumn('content');
});
We provide a scope to order the main model entries by its translation values.
For example, let's image we want to find the Post having a PostTranslation title equal to My first post.
Post::whereHas('translations', function ($query) {
$query
->where('locale', 'en')
->where('title', 'My first post');
})->first();
You can find more info at the Laravel Querying Relations docs. But we also provide several scopes to cover the most common scenarios.
If you see the following mysql error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'my_database.#sql-455_63'
(errno: 150) (SQL: alter table `country_translations`
add constraint country_translations_country_id_foreign foreign key (`country_id`)
references `countries` (`id`) on delete cascade)
Then your tables have the MyISAM engine which doesn't allow foreign key constraints. MyISAM was the default engine for mysql versions older than 5.5. Since version 5.5, tables are created using the InnoDB storage engine by default.
For tables already created in production, update your migrations to change the engine of the table before adding the foreign key constraint.
public function up()
{
DB::statement('ALTER TABLE countries ENGINE=InnoDB');
}
public function down()
{
DB::statement('ALTER TABLE countries ENGINE=MyISAM');
}
For new tables, a quick solution is to set the storage engine in the migration:
Schema::create('language_translations', function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
// ...
});
The best solution though would be to update your mysql version. And always make sure you have the same version both in development and production environment!
How can I help you explore Laravel packages today?