An Eloquent translator for Laravel
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.

README.md

Laravel Translator

laravel translator

An easy-to-use Eloquent translator for Laravel.

// Fetch an Eloquent object
$article = Article::find(1);

// Display title in default language
echo $article->title;

// Change the current locale to Swedish
App::setLocale('sv');

// Display title in Swedish
echo $article->title;

Build Status Coverage Status Total Downloads Latest Version License

Installation

Require this package, with Composer, in the root directory of your project.

$ composer require vinkla/translator

Create a new migration for the translations. In our case we want to translate the articles table.

$ php artisan make:migration create_article_translations_table

Make sure you add the article_id and locale columns. Also, make them unique.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * This is the article translations table seeder class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class CreateArticleTranslationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_translations', function (Blueprint $table) {
            $table->increments('id');

            $table->string('title'); // Translated column.

            $table->integer('article_id')->unsigned()->index();
            $table->foreign('article_id')
                ->references('id')
                ->on('articles')
                ->onDelete('cascade');

            $table->string('locale')->index();

            $table->unique(['article_id', 'locale']);

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('article_translations');
    }
}

Create a new empty ArticleTranslation Eloquent model.

use Illuminate\Database\Eloquent\Model;

/**
 * This is the article translation eloquent model class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class ArticleTranslation extends Model
{
    /**
     * A list of methods protected from mass assignment.
     *
     * @var string[]
     */
    protected $guarded = ['_token', '_method'];
}

Add the Translatable trait and the IsTranslatable interface to the Article Eloquent model. Add the has-many translations() relation method and fill the $translatable array with translatable attributes.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Vinkla\Translator\Translatable;

/**
 * This is the article eloquent model class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class Article extends Model
{
    use Translatable;

    /**
     * A list of methods protected from mass assignment.
     *
     * @var string[]
     */
    protected $guarded = ['_token', '_method'];

    /**
     * List of translated attributes.
     *
     * @var string[]
     */
    protected $translatable = ['title'];

    /**
     * Get the translations relation.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function translations(): HasMany
    {
        return $this->hasMany(ArticleTranslation::class);
    }
}

Now you're ready to start translating your Eloquent models!

Usage

Fetch pre-filled translated attributes.

$article->title;

Fetch translated attributes with the translate() method.

$article->translate()->title;

Fetch translated attributes for a specific locale with the translate() method.

$article->translate('sv')->title;

Fetch translated attributes without fallback support.

$article->translate('de', false)->title;

Fetch resources and eager load the translations.

$articles = Article::with('translations')->get();

Fetch resources and eager load the translations for a single locale.

$articles = Article::withTranslations('en')->get();

Create instance with translated attributes.

Article::create(['title' => 'Use the force Harry']);

Note that this package will automatically find translated attributes based on items from the $translatable array in the Eloquent model.

Create instance with translated attributes for a specific locale.

App::setLocale('sv');

Article::create(['title' => 'Använd kraften Harry']);

Update translated attributes.

$article->update(['title' => 'Whoa. This is heavy.']);

Update translated attributes for a specific locale.

App::setLocale('sv');

$article->update(['title' => 'Whoa. Detta är tung.']);

Delete an article with translations.

$article->delete();

Delete translations.

$article->translations()->delete();

Want more? Then you should definitely check out the tests. They showcase how to setup a basic project and are quite readable. Happy hacking!

License

MIT © Vincent Klaiber