DEV Community

Cover image for Translate text with google translate in your PHP/Laravel app with 4 lines of codes.
Eric The Coder
Eric The Coder

Posted on

Translate text with google translate in your PHP/Laravel app with 4 lines of codes.

Hi,

Here a quick way to easily translate text in your php Laravel application. NO NEED TO HAVE A GOOGLE API KEY!

First you need to install Google Translate PHP package.

You can do it by running in your project folder

$ composer require stichoza/google-translate-php 
Enter fullscreen mode Exit fullscreen mode

After installation you can use it anywhere in your code like this.

use Stichoza\GoogleTranslate\GoogleTranslate;

$tr = new GoogleTranslate(); 
$tr->setSource('en'); // Translate from English
$tr->setTarget('fr'); // Translate to French

echo $tr->translate('Hello World!'); // Bonjour le monde!
Enter fullscreen mode Exit fullscreen mode

That's it. Cannot be easier than that!

If you want to use more options like language auto-detect, etc. You can read the doc: https://github.com/Stichoza/google-translate-php

CONCLUSION

If you like this kind of small tips, you can follow me, I have more to come.

See you later...

Top comments (0)