Dynamic Translations

Handle Translations with ease without touching the source code

Goal

In real-life projects, we definitely don't want to put translations to the files in resources/lang

The drawback is: if you want to change any translations immediately, you have to change the code and deploy it. Takes time, right?

And here is it, Dynamic Translations built-in within ShipSaaS Ready, use it in no time!

Manage Translations

Visit: Entities/Translation for more details

Configuration

Base: saas-ready.translation

KeyValueDescription

strategy

single or all

  • single: will do a single query when getting the translated text

  • all: will get all translations then return the translated text (will be cached shortage)

should-cache

boolean

If turned on, it will use the all strategy to get all the translations, then put all the translations into the default cache driver.

Usage

Facade Style

use SaasReady\Facade\SaasTranslator;

// welcome-text = "Hello :user"
// this will give you: Hello Seth Phat
$welcomeText = SaasTranslator::translate('welcome-text', [
    'user' => 'Seth Phat',
]);

DI style

// WelcomeController.php
use SaasReady\Services\Translator;

public function welcome(Translator $translator): JsonResponse
{
    return new JsonResponse([
        'welcome' => $translator->translate(
            'welcome-text'
            [
                'user' => 'Seth Phat',
            ]
        ),
    ]);
}

Functional style

$welcomeText = saasTrans('welcome-text', [
    'user' => 'Seth Phat',
]);

Render Translations

If you wish to render the translation file (en.json, vi.json,...) and utilize the __() method of Laravel (for your Blade views or anything), then we have this command:

php artisan saas-ready:render-translation {langCode}

php artisan saas-ready:render-translation en
php artisan saas-ready:render-translation vi

It will render the json file and store it into your lang (new) or resources/lang (old)

Last updated