This package adds a client to translate text in Laravel using LibreTranslate.
LibreTranslate is a free and open source translation library.
You can install the package via composer:
composer require oss-tools/laravel-libretranslate
To set up the package, you will need to set the below env variables.
LIBRETRANSLATE_HOST=https://mylibretranslateserver.com
LIBRETRANSLATE_API_KEY=your-api-key
LIBRETRANSLATE_DEFAULT_SOURCE=en
Note: The default value for LIBRETRANSLATE_HOST
is set to https://translate.argosopentech.com however, we recommend setting up your own server or using a host that is suitable for your needs for production.
use OSSTools\LibreTranslate\Client;
use OSSTools\LibreTranslate\Translation\LanguageCodes;
class ExampleController extends Controller
{
public function translate()
{
$client = new Client();
// Returns an instance of \OSSTools\LibreTranslate\Translation\TranslationCollection
$result = $client->translate('This is some text', LanguageCodes::SPANISH);
// Returns an array of \OSSTools\LibreTranslate\Translation\TranslationItem
$result = $client->translate('This is some text', LanguageCodes::SPANISH)->getAll();
// Returns a single instance of \OSSTools\LibreTranslate\Translation\TranslationItem
$result = $client->translate(['This is some text', 'A test'], LanguageCodes::SPANISH)->first();
// Returns a single instance of \OSSTools\LibreTranslate\Translation\TranslationItem
$result = $client->translate(['This is some text', 'A test'], LanguageCodes::SPANISH)->last();
// Returns a single instance of \OSSTools\LibreTranslate\Translation\TranslationItem
$result = $client->translate(['This is some text', 'A test'], LanguageCodes::SPANISH)->get('A test');
// Returns "Una prueba"
$result = $client->translate(['This is some text', 'A test'], LanguageCodes::SPANISH)->last()->getText();
}
}
use OSSTools\LibreTranslate\Client;
class ExampleController extends Controller
{
public function translate()
{
$client = new Client();
// Returns an instance of \OSSTools\LibreTranslate\Translation\TranslationDetectionCollection
$result = $client->detect('This is some text');
// Returns an array of \OSSTools\LibreTranslate\Translation\TranslationDetectionItem
$result = $client->detect('This is some text')->getAll();
// Returns a single instance of \OSSTools\LibreTranslate\Translation\TranslationDetectionItem
$result = $client->translate('This is some text')->first();
// Returns "en"
$result = $client->detect('Some text')->first()->getLanguage();
// Returns "es"
$result = $client->detect('Una prueba')->first()->getLanguage();
}
}
composer test
The MIT License (MIT). Please see License File for more information.