Laravel 12 - Live Translator Using Google Translate.
Laravel 12 - Live Translator Using Google Translate.
In this tutorial, we will learn how to create a live translator in Laravel 12 using Google Translate. Type text in the textarea and see real-time translations instantly.
If you're a video person, feel free to skip the post and check out the video instead!
ďťżQuick Overview
In this guide, weâll walk you through adding Google Translate functionality to a Laravel 12 application using the stichoza/google-translate-php package. Youâll start by setting up a fresh Laravel project, either from scratch or using an existing application, with MySQL configured as the database. After installing the package, youâll create a controller to manage the translation logic and configure routes to connect the frontend and backend. The tutorial also includes a practical demo with two text areas, where you can type in any language on the left and instantly see the English translation on the right. Along the way, weâll explore shorthand methods to make translations even simpler, and finally, youâll test everything in the browser to ensure your Laravel application can provide seamless multilingual support.
Step # 1 : Create Your Laravel 12 Project.
Weâll start by getting a fresh Laravel 12 project up and running. You can either spin up a brand-new app or work with one you already have, totally your call. If youâre using the Laravel installer, just run
laravel new translate
Not a fan of the installer? Composer works just as well.
composer create-project laravel/laravel --prefer-dist translate
During setup, youâll be asked a few quick questions.
- Starter Kit: Pick None since we donât need any authentication scaffolding right now.
- Testing Framework: Choose Pest for a modern testing experience.
- Database: Go with MySQL.
- Migrations: Type yes so Laravel can create the default tables for you.
- Frontend build: Say yes to running npm install and npm run build so your frontend assets are ready.
Once thatâs done, youâll have a clean Laravel 12 project with MySQL connected and the frontend compiled. Perfect foundation to dive straight into adding the translation feature without worrying about extra setup.
Step # 2 : Navigate to the Project Directory.
Open a terminal window (such as Git Bash or Command Prompt) and navigate to the root directory of your Laravel project.
cd c:xampp/htdocs/translate
This puts you inside the project folder so you can run Artisan commands and manage your application.
Step # 3 : Install the Google Translate Package.
Next, add the Google Translate functionality by installing the stichoza/google-translate-php package. This can be done by running the following command in your terminal.
composer require stichoza/google-translate-php
This package enables seamless integration of Google Translate into your Laravel app. It can automatically detect languages, translate text into more than 100 supported languages, and even provides shorthand methods for quick translations. With this in place, youâll be able to give your app multilingual power without reinventing the wheel.
Step # 4 : Create a Translate Controller.
The next step is to create a controller that will handle all the translation logic for our application. Run the following Artisan command in your terminal to generate it.
php artisan make:controller TranslateController
Once the controller is created, open app/Http/Controllers/TranslateController.php and update it with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stichoza\GoogleTranslate\GoogleTranslate;
class TranslateController extends Controller
{
public function index()
{
return view('translate');
}
public function translate(Request $request)
{
$tr = new GoogleTranslate();
$tr->setSource('auto'); // detect language automatically
$tr->setTarget('en'); // always translate to English
// Translate the input text from the request and return it as a JSON response
$result = $tr->translate($request->text);
return response()->json(['translation' => $result]);
}
}
With this setup, the index() method simply loads the Blade view where users will type their text. The translate() method is where the magic happens. It receives the input from the frontend, automatically detects the language, translates it to English, and returns the result as a JSON response. This way, the frontend can instantly display the translated text without reloading the page, creating a smooth, interactive experience for anyone using the translator. Itâs a clean separation of concerns, keeping the translation logic centralized while allowing the interface to remain responsive and user-friendly.
Step # 5 : Define Routes.
Open routes/web.php and add the following.
use App\Http\Controllers\TranslateController;
Route::get('/', [TranslateController::class, 'index']);
Route::post('/translate', [TranslateController::class, 'translate']);
The / route displays the translator page, while /translate handles Ajax requests for translation.
Step # 6 : Create the Blade View for the Translator.
Next, weâll build the frontend where users can interact with our translator. Inside the resources/views folder, create a new file called translate.blade.php and add the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shotcut - Laravel 12 Translator</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 min-h-screen flex items-center justify-center p-6 text-gray-100">
<div class="w-full max-w-6xl bg-gray-800 rounded-2xl shadow-2xl p-10">
<h1 class="text-4xl font-extrabold text-center text-indigo-400 mb-10 tracking-wide flex items-center justify-center gap-3">
đ Code Shotcut - Simple Translator Demo đ
</h1>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<!-- Source Text -->
<div class="flex flex-col">
<label for="source" class="mb-3 text-gray-300 font-semibold text-lg">Enter Text</label>
<textarea id="source"
class="w-full h-72 p-5 border border-gray-600 rounded-xl resize-none
focus:ring-2 focus:ring-indigo-500 focus:outline-none bg-gray-900 text-gray-100 placeholder-gray-500"
placeholder="Type text here..."></textarea>
</div>
<!-- Target Text -->
<div class="flex flex-col">
<label for="target" class="mb-3 text-gray-300 font-semibold text-lg">Translation</label>
<textarea id="target" readonly
class="w-full h-72 p-5 border border-gray-600 rounded-xl resize-none
bg-gray-700 text-gray-300 placeholder-gray-500 focus:outline-none"
placeholder="Translation will appear here..."></textarea>
</div>
</div>
</div>
<script>
const source = document.getElementById('source');
const target = document.getElementById('target');
const csrf = document.querySelector('meta[name="csrf-token"]').content;
let timeout = null;
source.addEventListener('input', function () {
const text = source.value.trim();
// Clear previous timeout
clearTimeout(timeout);
// If the input is empty, clear the translation field immediately
if (text === '') {
target.value = '';
return;
}
// Otherwise, wait 500ms after typing stops to send translation request
timeout = setTimeout(() => {
fetch('/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrf
},
body: JSON.stringify({ text: source.value })
})
.then(res => res.json())
.then(data => {
target.value = data.translation;
});
}, 500);
});
</script>
</body>
</html>
This view creates a sleek, dark-themed translator interface using Tailwind CSS via CDN. Users can type text on the left in any language, and as they type, the input is sent to the Laravel backend via Ajax. The backend processes the translation and instantly returns the result, which appears on the right in real time, giving users immediate feedback. Using Tailwind allows the interface to be clean, responsive, and visually appealing without requiring extra CSS setup. This approach provides a modern, interactive experience where translations are fast and seamless.
Step # 7 : Test the Translation.
Start your Laravel development server.
php artisan serve
Then open your browser and go to: http://127.0.0.1:8000.Try typing in German, Spanish, French, Hindi, or any other language in the left textarea. Youâll instantly see the English translation on the right side.
Shorthand Static Method for Quick Translations :
The Google Translate package provides a shorthand method to translate text without creating an instance. Add this to your TranslateController.
use Stichoza\GoogleTranslate\GoogleTranslate;
public function quickDemo()
{
// This directly translates "Bienvenido a Code Shortcut" from Spanish to English
return GoogleTranslate::trans('Bienvenido a Code Shortcut', 'en', 'es');
}
This static method is ideal for quick translations or small text snippets, while the textarea example is better for interactive input. To test it, create a route in routes/web.php pointing to this method.
Route::get('/quick-demo', [App\Http\Controllers\TranslateController::class, 'quickDemo']);
Then visit: http://127.0.0.1:8000/quick-demo to see the translation appear instantly. This approach is perfect for quick checks, while the interactive textarea is better for live typing and dynamic translations.
Conclusion
By following this guide, youâve successfully added Google Translate functionality to your Laravel 12 application using the stichoza/google-translate-php package. You now have a practical, interactive demo where typing in one box instantly displays the translated text in the other. Along the way, you learned how to set up a fresh Laravel 12 project, install and configure the Google Translate package, build a controller to handle live translation, define routes to connect the frontend and backend, create a Blade view with two text areas, and implement Ajax logic for real-time updates. You also explored shorthand static methods for quick translations. This integration opens up numerous possibilities, from creating multilingual websites to building engaging language-learning tools, giving your Laravel project a more global reach.
For more advanced features and options, check out the official stichoza/google-translate-php documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyoneâs talking about.
0 Comments