Official Doc
https://github.com/dimsav/laravel-translatable#tutorials
Schema
Main table: store_menu, translated table: store_menu_translations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
Schema::create('store_menu', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('store_id'); /* Don't need to add columns need to be translated in main table */ $table->tinyInteger('status')->default(1); $table->timestamps(); $table->softDeletes(); }); Schema::create('store_menu_translations', function (Blueprint $table) { $table->increments('id'); $table->string('locale')->index(); $table->bigInteger('store_menu_m_id')->unsigned(); /* $table->bigInteger('menu_id')->unsigned(); I tried to use this column name to reference to main table, but error occurs when saveing data and it says 'store_menu_m_id' not found. Have no idea where to change the rule */ // Columns need to be translated $table->string('name')->nullable(); $table->string('subtitle', 255)->nullable(); $table->text('summary')->nullable(); $table->longText('description')->nullable(); $table->text('note')->nullable()->nullable(); $table->unique(['store_menu_m_id','locale']); $table->foreign('store_menu_m_id')->references('id')->on('store_menu')->onDelete('cascade'); }); |
Full example:
Controller to save data
1 2 3 4 |
$menu = new StoreMenuM; $menu = TranslateM::to_translate_data($data, $menu); //logg($menu); $menu->save(); |
TranslateM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace App\Models; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Config; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class TranslateM extends Model{ static function to_translate_data($data, $model){ $locales = Config::get('wikirex.locales'); //logg($data); foreach ($data as $key => $value) { $match = null; foreach ($locales as $code => $locale) { preg_match('/^(.+)\_(' . $code . ')$/', $key, $match); //logg($match); if($match != false){ break; } } //logg($match); if($match == false){ $model->{$key} = $value; }else{ $model->translateOrNew($match[2])->{$match[1]} = $value; } } return $model; } } |