Table of contents

laravel google translate

In this post, we will tackle Laravel Google Translate if your project is designed as multilingual and you don't want to translate manually every time you add a new language. Then this Laravel package we will use can help you to implement your Laravel google translate.

 

The good side of this package is don't need any keys to access the API and is easy to implement. But they are lowering the number of allowed requests per IP in a certain amount of time, leading you to ban your IP. You should try sending less to stay under the radar of your IP. For more details about this issue kindly visit their documentation: https://github.com/Stichoza/google-translate-php.

 

Okay so let's continue.

 

 

Step 1: Install the package

composer require stichoza/google-translate-php

 

 

Step 2: Usage

Now, let's implement the translation using this package. In your controller you need to use the following class:

 

use Stichoza\GoogleTranslate\GoogleTranslate;

 

Then call it to your controller method.

$tr = new GoogleTranslate('de');

echo $tr->translate('Hello World!');

 

Another example is using a static method which is you don't need to instantiate the class and put in a variable.

echo GoogleTranslate::trans('Hello World!', 'de');

 

 

As you can see we want to translate the "Hello World!" to German. And the result is this.

laravel google translate

Here is the complete code:

<?php

namespace App\Http\Controllers;

use Stichoza\GoogleTranslate\GoogleTranslate;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index() 
    {

        $tr = new GoogleTranslate('de');

        echo $tr->translate('Hello World!');
    }
}

 

That's it. I hope it helps :)