PHP code example of syriable / laravel-translations

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

    

syriable / laravel-translations example snippets


use Syriable\Translations\Facades\Translations;

Translations::import();                            // lang files  → database
Translations::set('auth.failed', 'Echec', 'fr');   // write a value
Translations::get('auth.failed', 'fr');            // 'Echec'
Translations::translate('auth.failed', 'de');      // AI translation
Translations::export();                            // database → lang files

'source_locale' => env('TRANSLATIONS_SOURCE_LOCALE', 'en'),  // the language you author in
'lang_path'     => env('TRANSLATIONS_LANG_PATH', lang_path()), // where import reads / export writes

'database' => [
    'connection' => env('TRANSLATIONS_DB_CONNECTION'),
    'prefix'     => env('TRANSLATIONS_DB_PREFIX', 'tx_'),
],

use Syriable\Translations\Facades\Translations;

// Read a value for a locale (defaults to the source locale when omitted)
Translations::get('cart.checkout', 'es');     // 'Pagar' or null
Translations::has('cart.checkout', 'es');     // bool

// Write a value — creates the phrase (and seeds every locale) on demand
Translations::set('cart.checkout', 'Pagar', 'es');

// With metadata recorded on the revision
Translations::set('cart.checkout', 'Pagar', 'es', [
    'by'     => 'maria',                          // author, stored on the revision
    'reason' => 'manual',                         // manual|import|ai|rollback|bulk
    'status' => \Syriable\Translations\Enums\MessageStatus::Approved,
    'meta'   => ['source' => 'support-ticket'],
]);

// Resaving the exact same value is a no-op: no revision, no status/actor change
Translations::set('cart.checkout', 'Pagar', 'es');
Translations::set('cart.checkout', 'Pagar', 'es'); // ignored - value didn't change

// Clear a single locale's value (keeps the phrase), or delete the phrase entirely
Translations::forget('cart.checkout', 'es');   // value → null, status → open
Translations::forget('cart.checkout');         // deletes the phrase across all locales

// Every value for a locale, keyed by dotted key
Translations::all('es');                       // ['cart.checkout' => 'Pagar', ...]

Translations::similar('validation.accepted');
// Collection<Phrase>: accepted_if, accepted_unless, ...

Translations::similar('validation.accepted')->map->dottedKey();
// ['validation.accepted_if', 'validation.accepted_unless']

// Options
Translations::similar('validation.accepted', [
    'segments'     => 1,      // how many leading segments must match (default 1)
    'limit'        => 5,      // cap the number of results
    '

Translations::locales();                       // Collection<Locale>, ordered by code

// Add a target locale — metadata (name, native name, RTL) is auto-detected and every
// existing phrase is seeded an "open" message for it
Translations::addLocale('de');

// Mark a locale as the source
Translations::addLocale('en', ['is_source' => true]);

// Override auto-detected metadata (name, native_name, direction, tone, enabled)
Translations::addLocale('xx-custom', [
    'name'        => 'Custom Locale',
    'native_name' => 'Locale personnalisée',
    'direction'   => \Syriable\Translations\Enums\Direction::Rtl,
    'tone'        => \Syriable\Translations\Enums\Tone::Formal,
]);

$summary = Translations::import();                       // returns an ImportSummary
$summary = Translations::import(['fresh' => true]);      // clear everything first
$summary = Translations::import(['overwrite' => false]); // keep existing values

$summary->localeCount;  // 3
$summary->phraseCount;  // 412
$summary->createdCount; // 1180
$summary->updatedCount; // 0

Translations::export();                          // everything
Translations::export(['locale' => 'es']);        // one locale
Translations::export(['bundle' => 'auth']);      // one bundle

// Translate one key into a locale (writes the result, marks it ai_generated)
Translations::translate('cart.checkout', 'de');

// The AI service for finer control
$ai = Translations::ai();   // MachineTranslation

$ai->translateOpen($germanLocale);               // translate every untranslated message; returns count
$ai->suggest($phrase, $germanLocale, ['variants' => 3]); // TranslationResult, without saving
$ai->apply($phrase, $germanLocale, [             // translate + save the best variant
    'tone'     => 'formal',                       // neutral|formal|informal|friendly|technical
    'glossary' => true,                           // 

use Syriable\Translations\Ai\AiProviders;

AiProviders::usable();                 // Collection<AiProvider> — e.g. [OpenAI, Anthropic]
AiProviders::usable()->map->getLabel(); // ['OpenAI', 'Anthropic']

$result = $ai->suggest($phrase, $germanLocale, ['variants' => 3]);

$result->best();        // the clean translation to store/copy (from base_value)
$result->proposed();    // the translation exactly as the model phrased it (may 

use Syriable\Translations\Contracts\Translator;
use Syriable\Translations\Ai\FakeTranslator;

$this->app->instance(Translator::class, new FakeTranslator(
    fn ($request) => strtoupper($request->text),
));

$quality = Translations::quality();   // Inspector

$quality->scan();                     // check every translated message; returns a stats array
$quality->scan($localeId);            // limit to one locale
// ['error' => 2, 'warning' => 5, 'info' => 1, 'checked' => 412]

$quality->inspect($message);          // array<Issue>, without persisting
$quality->inspectAndStore($message);  // persist QualityIssue rows for one message
$quality->fix($qualityIssue);         // auto-fix a fixable issue (whitespace, casing); returns bool
$quality->fix($qualityIssue, 'qa-bot'); // optional `by`; falls back to ResolvesActor like every other write

$review = Translations::aiReview();          // MachineReview

$result = $review->review($germanLocale);    // ReviewResult — reviews every translated message
$review->review($germanLocale, [
    'phrase_ids' => [1, 2, 3],                // limit the review to specific phrases
    'provider'   => 'anthropic',             // validated against ai.allowed_providers
]);

$result->hasIssues();          // bool
$result->issues;               // array<ReviewIssue>{ key, severity, description, suggestion, baseSuggestion }
$result->forKey('cart.checkout'); // the issues reported for one dotted key
$result->countsBySeverity();   // ['high' => 1, 'medium' => 3, 'low' => 0]

use Syriable\Translations\Contracts\Reviewer;
use Syriable\Translations\Ai\FakeReviewer;
use Syriable\Translations\Enums\ReviewSeverity;
use Syriable\Translations\Support\ReviewIssue;

$this->app->instance(Reviewer::class, new FakeReviewer(
    fn ($request) => [new ReviewIssue('cart.checkout', ReviewSeverity::Medium, 'Too informal.', 'Use the formal register.')],
));

use Syriable\Translations\Rules\TranslationPlaceholdersRule;
use Syriable\Translations\Rules\TranslationPluralRule;

$request->validate([
    'value' => [
        ' selectors/segments match the source
    ],
]);

$glossary = Translations::glossary();   // Glossary

$term = $glossary->define('invoice', note: 'billing document', wholeWord: true);
$glossary->translate($term, $spanishLocale->id, 'factura', approvedBy: 'maria');

$glossary->pairsFor('Download your invoice', $spanishLocale->id);  // ['invoice' => 'factura']
$glossary->matching('Download your invoice', $spanishLocale->id);  // Collection<Term>
$glossary->forget($term);

$revisions = Translations::revisions();   // RevisionRollback

$revisions->toRevision($revision);                       // restore a message to a past revision
$revisions->byMember('maria');                           // undo every change a contributor made
$revisions->byMember('maria', from: '2026-01-01', to: '2026-02-01');
$revisions->afterDate('2026-06-01', localeId: $es->id);  // undo changes after a cutoff

$revision->changed_by;   // '42' - the raw stored id
$revision->member;       // App\Models\User { id: 42, ... } - via belongsTo

$this->app->bind(ResolvesActor::class, MyQueueAwareActorResolver::class);

$review = Translations::review();   // ReviewFlow

use Syriable\Translations\Enums\MemberRole;

$review->statusForSave(MemberRole::Translator);   // MessageStatus::PendingReview
$review->statusForSave(MemberRole::Reviewer);     // MessageStatus::Approved

$review->approve($message, 'lead-reviewer');
$review->reject($message, 'Too informal', 'lead-reviewer');

$message->comment('Needs a more formal tone.', memberId: 'maria');
$message->comments;   // HasMany Comment

$insights = Translations::insights();   // Insights

$insights->dashboard();          // cached bundle of everything below
$insights->coverage();           // per-locale: total / translated / approved / percent
$insights->bundleCoverage();     // per-bundle progress (per lang file)
$insights->overallCoverage();    // single float across all target locales
$insights->leaderboard();        // top contributors by change count
$insights->velocity(days: 30);   // changes per day
$insights->stale($localeId);     // Message models older than analytics.stale_after_days
$insights->staleCounts();        // stale counts keyed by locale_id
$insights->flush();              // drop the cache (also flushed automatically on writes/imports)

use Syriable\Metrics\Facades\Metrics;

$coverage = Metrics::run('translations.coverage');
$coverage->groups('coverage');             // per-locale partition breakdown
$coverage->value('translated');            // aggregate across all locales

$quality = Metrics::run('translations.quality');
$quality->value('quality');                // weighted review + validation score

$velocity = Metrics::run('translations.velocity', ['range' => '30d']);
$velocity->points('changes');              // daily revision counts

$bundles = Metrics::run('translations.bundle_coverage');
$bundles->groups('percent');               // per-bundle completion %

// Record where each translation key is used (for richer AI context)
Translations::scanUsage();              // scans config('translations.scanning.paths')
Translations::scanUsage('resources/views');

// Detect hardcoded, untranslated strings (false-positive filter + ignore list)
Translations::scanLoose();

use Syriable\Translations\Support\ActivityRecorder;

app(ActivityRecorder::class)->log('glossary.updated', $term, ['field' => 'value'], memberId: 'maria');

return [
    // The language you author in; every other locale is a translation target.
    'source_locale' => env('TRANSLATIONS_SOURCE_LOCALE', 'en'),

    // Where import reads and export writes.
    'lang_path' => env('TRANSLATIONS_LANG_PATH', lang_path()),

    // Package tables are prefixed and may use a dedicated connection.
    'database' => [
        'connection' => env('TRANSLATIONS_DB_CONNECTION'),
        'prefix'     => env('TRANSLATIONS_DB_PREFIX', 'tx_'),
    ],

    // The model that represents whoever translates/reviews/manages. Defaults
    // to your app's own user model. The package doesn't own a table for it.
    'member_model' => env('TRANSLATIONS_MEMBER_MODEL', config('auth.providers.users.model', 'App\\Models\\User')),

    // Auto-resolving "who did this" when a write omits `by` (see Contracts\ResolvesActor).
    // auth_guard: null uses your app's default guard. system_actor: recorded when nobody's
    // authenticated (console/queue); null keeps unattended runs unattributed.
    'auth_guard' => env('TRANSLATIONS_AUTH_GUARD'),
    'system_actor' => env('TRANSLATIONS_SYSTEM_ACTOR'),

    'import' => [
        'scan_vendor'         => true,   // import vendor/<ns>/<locale>/*.php
        'detect_placeholders' => true,   // extract :name and {count}
        'detect_html'         => true,
        'detect_plural'       => true,
        'exclude_files'       => ['pagination.php'],
    ],

    'export' => [
        'sort_keys'     => true,
        'exclude_empty' => true,
        'approved_only' => env('TRANSLATIONS_EXPORT_APPROVED_ONLY', false),
    ],

    'review' => [
        'enabled' => env('TRANSLATIONS_REVIEW', true),
    ],

    'revisions' => [
        'enabled'        => true,
        'retention_days' => 90,
    ],

    // Automatic activity feed for status changes and comments.
    'activities' => [
        'enabled' => true,
    ],

    'ai' => [
        'enabled'           => env('TRANSLATIONS_AI', false),
        'provider'          => env('TRANSLATIONS_AI_PROVIDER', 'openai'),
        'model'             => env('TRANSLATIONS_AI_MODEL', 'gpt-4o-mini'),
        'allowed_providers' => array_column(AiProvider::cases(), 'value'), // Syriable\Translations\Enums\AiProvider
        'variants'          => 3,
        'batch_size'        => 20,
        'review'            => ['batch_size' => 50], // source/target pairs per AI quality-review request
        'context'           => true, // 
bash
php artisan vendor:publish --tag=translations-config
php artisan vendor:publish --tag=translations-migrations   # optional, only to customize them
php artisan vendor:publish --tag=translations-lang         # optional, package UI strings
php artisan migrate
bash
php artisan translations:ai-review de --provider=anthropic