Laravel Translations is a Laravel package that provide translations for your models.
Install the package
composer require bramalho/laravel-translations
Add the service provider in app/config/app.php
BRamalho\LaravelTranslations\LaravelTranslationsServiceProvider::class,
Publish the configs
php artisan vendor:publish --provider 'BRamalho\LaravelTranslations\LaravelTranslationsServiceProvider'
Run migrations
php artisan migrate
Add the trait to your model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use BRamalho\LaravelTranslations\Translate;
class Page extends Model
{
use Translate;
protected $fillable = ['title', 'body'];
}
Add to your new table translations
data according to your model
<?php
use Illuminate\Database\Seeder;
use App\Page;
use BRamalho\LaravelTranslations\Translation;
class PageTableSeeder extends Seeder
{
public function run()
{
Page::create([
'id' => 1,
'title' => 'Hello World!',
'body' => 'This is my page'
]);
Translation::create([
'id' => 1,
'translation_id' => 1,
'translation_type' => App\Page::class,
'language' => 'pt',
'content' => [
'title' => 'Olá Mundo!',
'body' => 'Esta é a minha página'
]
]);
}
}
Then you can simply use it like:
<h1>{{ $page->translation->content['title'] ?? $page->title }}</h1>
<p>{!! $page->translation->content['body'] ?? $page->body !!}</p>
The Laravel Translations is open-sourced software licensed under the MIT license.