PHP code example of vortech / laravel-localize

1. Go to this page and download the library: Download vortech/laravel-localize 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/ */

    

vortech / laravel-localize example snippets


use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Vortech\Localize\Attributes\Localized;
use Vortech\Localize\HasLocales;

#[Fillable('sku', 'price', 'stock')]
#[Localized('slug', 'name', 'description')]
class Product extends Model
{
    use HasLocales;
}

Schema::create('product_translations', function (Blueprint $table): void {
    $table->id();

    $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();

    $table->string('locale', 35);
    $table->string('slug')->nullable();
    $table->string('name')->nullable();
    $table->text('description')->nullable();
    $table->timestamps();

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

$product->locale()->name;                         // in the app locale
$product->locale('en')->name;                     // in English, falling back to the app locale
$product->locale('en', fallback: false)->name;    // only what is stored for English, else null

// hu: name = 'Fekete póló', description = 'Pamut póló'
// en: name = 'Black T-shirt', description = null

$product->locale('en')->name;                          // Black T-shirt
$product->locale('en')->description;                   // Pamut póló
$product->locale('de')->name;                          // Fekete póló
$product->locale('en', fallback: false)->description;  // null

#[Localized('slug', 'name', 'description', magic: true)]
class Product extends Model { use HasLocales; }

$product->name;                  // the same as $product->locale()->name (the current app locale)
$product->locale('hu')->name;    // an explicit locale keeps working
$product->name = 'x';            // LogicException: write with locale()->update() or saveLocales()

// one locale, saved immediately
$product->locale('en')->update([
    'name' => 'Black T-shirt',
    'slug' => 'black-t-shirt',
]);

// several locales, in one transaction
$product->saveLocales([
    'hu' => ['name' => 'Fekete póló'],
    'en' => ['name' => 'Black T-shirt', 'description' => null],
]);

$product = DB::transaction(fn (): Product => Product::create([...])->saveLocales([
    'hu' => ['name' => 'Fekete póló', 'slug' => 'fekete-polo'],
    'en' => ['name' => 'Black T-shirt', 'slug' => 'black-t-shirt'],
]));

use Vortech\Localize\Rules\UniqueTranslation;

// a fixed locale
'slug' => ['bail', 'e shorthand ignores the model itself
'slug' => ['bail', 'iqueTranslation::for(Product::class, 'slug')
        ->localeFrom('translations.*.slug')
        ->ignore($product)],

$products = Product::query()->withLocales()->get();

foreach ($products as $product) {
    echo $product->locale('en')->name;
}

Product::query()->withLocales(['en'])->get();

Product::query()->withLocales(['en'], fn ($rows) => $rows->whereNotNull('slug'))->get();

$product->locale('en')->toArray();   // ['slug' => ..., 'name' => ..., 'description' => ...]

// edit forms: no fallback, so a fallback text is not mistaken for a finished translation
$form = [
    'hu' => $product->locale('hu', fallback: false)->toArray(),
    'en' => $product->locale('en', fallback: false)->toArray(),
];

Event::listen(function (TranslationChanged $event) {
    // $event->model     the owner (Product)
    // $event->key       'name'
    // $event->locale    'hu'
    // $event->oldValue  null on a new row
    // $event->newValue
});

Product::query()->whereLocale('name', 'en')->get();              // models with an English name
Product::query()->whereLocales('name', ['en', 'hu'])->get();     // with a name in English or Hungarian

Product::query()
    ->whereHasLocale('en', fn ($query) => $query->where('slug', 'black-t-shirt'))
    ->withLocales()
    ->firstOrFail();

Product::query()->whereHasLocale('de')->get();    // models that have a German row at all

Product::factory()->withLocales([
    'hu' => ['name' => 'Fekete póló'],
    'en' => ['name' => 'Black T-shirt'],
])->create();

Product::factory()->withLocales(['hu', 'en'], ['name' => 'Póló'])->create();                  // same values for each locale
Product::factory()->withLocales(['hu', 'en'], [['name' => 'Póló'], ['name' => 'Tee']])->create(); // one entry per locale

Route::localized(function (): void {
    Route::get('products/{product}', [ProductController::class, 'show'])->name('products.show');
});
// /hu/products/1, /en/products/1, /pt_BR/products/1 ...

Route::localized(fn () => ..., ['hu', 'en']);   // locales for this group only

#[Localized('slug', 'title', 'body')]
#[LocalizedSlug(from: 'title', to: 'slug')]   // these are the defaults 'name' and 'slug'
class Article extends Model
{
    use HasLocales;
}

$article->saveLocales(['hu' => ['title' => 'Fekete póló']]);   // slug: fekete-polo

Route::localized(function (): void {
    Route::get('articles/{article}', [ArticleController::class, 'show'])->name('articles.show');
    Route::get('articles/{article:id}/edit', [ArticleController::class, 'edit'])->name('articles.edit');
});

route('articles.show', $article);   // /hu/articles/fekete-polo, the slug of the current locale

$links = app(LocaleLinks::class);

$links->all();         // every locale: ->locale, ->url (null without a translation), ->current, ->available()
$links->alternates();  // only the available ones, without the query string
$links->canonical();   // this page in the current locale, without the query string

#[Localized('title', 'features', casts: ['features' => 'array'])]
class Reference extends Model { use HasLocales; }

$reference->saveLocales(['hu' => ['features' => [['icon' => 'bolt', 'title' => 'Gyors']]]]);

$reference->locale('hu')->features;   // [['icon' => 'bolt', 'title' => 'Gyors']]
bash
php artisan localize:table Product
php artisan localize:table              # asks which model, from the ones in app/ that use HasLocales