Table of contents
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.
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 :)
Read next