Translating Text in Laravel Made Easy with TranslateTextHelper and Google Translate Library A Comprehensive Guide

Table of Contents

Introduction:

Translation of text is a common requirement for many web applications that need to support users from different regions speaking different languages. In Laravel, we can use third-party libraries to translate text from one language to another. In this blog, we will discuss a helpful code snippet for translating text using the Google Translate PHP library.

Problem Statement:

The need for language translation arises when we want to support users who speak different languages. We may need to translate dynamic content at runtime, such as user-generated content, comments, or messages. The code we are discussing here provides a solution for this problem.

The code we are discussing here is a helper class named TranslateTextHelper that uses the Google Translate PHP library. The TranslateTextHelper class has two static variables $source and $target, which hold the source and target language codes, respectively. The class provides two methods to set these variables, setSource() and setTarget(). The translate() method takes a string as input and returns the translated string.

Here is the code for the TranslateTextHelper class:

				
					<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Log;
use Stichoza\GoogleTranslate\Exceptions\LargeTextException;
use Stichoza\GoogleTranslate\Exceptions\RateLimitException;
use Stichoza\GoogleTranslate\Exceptions\TranslationRequestException;
use Stichoza\GoogleTranslate\GoogleTranslate;

class TranslateTextHelper
{
    /**
     * @var string Default source language.
     */
    private static string $source = 'en';

    /**
     * @var string Default target language.
     */
    private static string $target = 'ar';

    /**
     * Set the source language.
     *
     * @param  string  $source The source language code.
     * @return self This instance of the class.
     */
    public static function setSource(string $source): self
    {
        self::$source = $source;

        return new self();
    }

    /**
     * Set the target language.
     *
     * @param  string  $target The target language code.
     * @return self This instance of the class.
     */
    public static function setTarget(string $target): self
    {
        self::$target = $target;

        return new self();
    }

    /**
     * Translate the given text from the source language to the target language.
     *
     * @param  string  $text The text to be translated.
     * @return string The translated text.
     */
    public static function translate(string $text): string
    {
        $translatedText = '';

        try {
            $translator = new GoogleTranslate();
            $translator->setSource(self::$source);
            $translator->setTarget(self::$target);

            $translatedText = $translator->translate($text);
        } catch (LargeTextException|RateLimitException|TranslationRequestException $ex) {
            Log::error('TranslateTextHelperException', [
                'message' => $ex->getMessage(),
            ]);
        }

        return $translatedText;
    }
}
				
			

How to use this code:

To use this code, we need to include the Google Translate PHP library in our Laravel application. We can do this by installing the library using Composer:

				
					composer require stichoza/google-translate-php
				
			

After installing the library, we can use the TranslateTextHelper class to translate text. Here is an example of how to use the TranslateTextHelper class to translate a string:

				
					use App\Helpers\TranslateTextHelper;

// Set the source and target languages
TranslateTextHelper::setSource('en')->setTarget('ar');

// Translate the text
$translatedText = TranslateTextHelper::translate('Hello, world!');

// Output the translated text
echo $translatedText;
				
			

In this example, we first set the source and target languages using the setSource and setTarget methods, respectively. Then, we call the translate method to translate the text. The translated text is stored in the $translatedText variable, which we then output to the screen.

Note:stichoza/google-translate-php package may work without an API key,it is based on crawling the Google Translate website.

You can find more information about this package by visiting the following link:
https://github.com/Stichoza/google-translate-php

Conclusion:

In conclusion, the TranslateTextHelper class is a simple and useful tool for translating text from one language to another in your Laravel projects. By using the google-translate-php library, this class provides a reliable and easy-to-use solution for translating text at runtime.

Credit to Library Owner:

I would like to give credit to the owner of the google-translate-php library, Stichoza, for creating such a useful tool for PHP developers. Without their hard work and dedication, this class would not be possible. The library can be found at https://github.com/Stichoza/google-translate-php.

Popular Post

Leave a Reply

Your email address will not be published. Required fields are marked *