PHP code example of alexkramse / laravel-translatable-table

1. Go to this page and download the library: Download alexkramse/laravel-translatable-table library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alexkramse / laravel-translatable-table example snippets


use Alexkramse\LaravelTranslatableTable\Traits\HasTranslatableTable;

class Post extends Model
{
use HasTranslatableTable;

    protected $fillable = ['slug', 'content'];

    public function translatableTableAttributes(): array
    {
        return ['title', 'description'];
    }
}

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ArticleTranslation extends Model
{
    use HasFactory;

    protected $guarded = [];
}

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

class CreateArticleTranslationsTable extends Migration
{
    public function up()
    {
        Schema::create('article_translations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('article_id')->constrained()->onDelete('cascade');
            $table->string('locale', 5)->nullable(false)->index();
            $table->string('title')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();

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

    public function down()
    {
        Schema::dropIfExists('article_translations');
    }
}

return [
    'locales' => [
        'en' => 'English',
        'es' => 'Spanish',
        'fr' => 'French',
    ],
    'translation_model_suffix' => 'Translation',
    'attribute_name' => 'i18n',
];

$post = Post::create([
    'slug' => 'example-post',
    'content' => 'This is the content.',
    'i18n' => [
        'en' => ['title' => 'Example Post', 'description' => 'An example post description.'],
        'fr' => ['title' => 'Exemple de publication', 'description' => 'Une description de publication.'],
    ],
]);

// Access translations
$title = $post->title; // Retrieves the title based on the current locale
$translations = $post->i18n; // Retrieves all translations
bash
php artisan vendor:publish --tag=config --provider="Alexkramse\LaravelTranslatableTable\TranslatableTableServiceProvider"