PHP code example of lundo / laravel-translations

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

    

lundo / laravel-translations example snippets


use Lundo\Translations\Traits\HasTranslations;

class Article extends Model
{
    use HasTranslations;

    protected array $translatable = ['title', 'body'];
}

app()->setLocale('en');

$article->title; // returns English translation, or the NL column value if none exists

$article->getTranslation('title', 'en'); // null if not set
$article->getTranslations('title');      // ['nl' => 'Titel', 'en' => 'Title', 'fr' => '...']

$article->hasTranslation('title', 'en'); // bool

$article->locales(); // ['nl', 'en', 'fr']

app()->setLocale('en');

$article->title = 'English title';
$article->save(); // writes to translations table

$article->setTranslation('title', 'en', 'English title');
$article->setTranslation('title', 'nl', 'Nederlandse titel'); // writes to model column

$article->setTranslations('title', [
    'nl' => 'Nederlandse titel',
    'en' => 'English title',
    'fr' => 'Titre français',
]);

$article->forgetTranslation('title', 'en');   // remove one key for a locale
$article->forgetAllTranslations('en');         // remove all keys for a locale

use Illuminate\Validation\Rule;
use Lundo\Translations\Rules\LocalizedRule;
use Lundo\Translations\Rules\LocaleRequiredRule;

Rule::macro('localized', fn (...$args) => new LocalizedRule(...$args));
Rule::macro('localeRequired', fn (...$args) => new LocaleRequiredRule(...$args));

// Request rules
'title' => [Rule::localized()],           // optional locales
'title' => [Rule::localeRequired()],      // all locales 

use Lundo\Translations\Traits\HasTranslations;
use Lundo\Translations\Traits\HasLocalizedMedia;

class Article extends Model
{
    use HasTranslations, HasLocalizedMedia;
}

// In your controller / view:
$article->getLocalizedMedia('photos');           // active locale
$article->getLocalizedMedia('photos', 'en');     // explicit locale

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Lundo\Translations\Middleware\SetLocaleFromUser::class);
})

// config/translations.php
'user_locale_attribute' => 'preferred_locale',

use Lundo\Translations\Scopes\WithActiveLocaleScope;

protected static function booted(): void
{
    static::addGlobalScope(new WithActiveLocaleScope);
}
bash
php artisan migrate
bash
php artisan vendor:publish --tag=translations-migrations
bash
php artisan vendor:publish --tag=translations-config