How to Add Google Translate in Laravel

Sovary August 27, 2022 1.01K
5 minutes read

Laravel support multi language using localization, but it required setting in configuration files. With Google Translate you don't have to do more hard work. Today tutorial we will discuss on how to use Google Translator with Laravel. We will guide how to use Google Translate API with Laravel app in easy with simple package installation.

In example below, I will install Google Translate Package in Laravel and we will not add any API key, we use package "stichoza/google-translate-php" by install via composer. Then we will create simple webpage with languages dropdown so that we can switch from one to other languages and the content in webpage will translate base on the selection. Anyway, this example work with Laravel 6, Laravel 7, Laravel 8 and Laravel 9 version.

Add Google Translate in Laravel

Following these steps below to integrate Google Translate in Laravel App:

  • Step 1 - Install Laravel
  • Step 2 - Install Google Translate Package
  • Step 3 - Create Middleware
  • Step 4 - Register Middleware
  • Step 5 - Create Controller
  • Step 6 - Add Mapping Route
  • Step 7 - Create Blade File
  • Step 8 - Run Laravel Server

Step 1 - Install Laravel

First of all, we will download fresh Laravel project. You can read this to know how to install Laravel project, you can skip the configure database connection as we are not required to do in this example.

Step 2 - Install Google Translate Package

This step we required a package name "stichoza/google-translate-php so we will run below command to download the library.

composer require stichoza/google-translate-php

Then aliase named in config file. Open the file and add the following to array providers

Open file app -> config.php

<?PHP
  
    ...
  
    'aliases' => Facade::defaultAliases()->merge([
        'GoogleTranslate' => Stichoza\GoogleTranslate\GoogleTranslate::class
    ])->toArray(),
  
];

Step 3 - Create Middleware

Now we will filter session language that we choose selection in dropdown. Let's create middleware file by following command

php artisan make:middleware LanguageMiddleware

The file will generate in location below

Open file app -> Http -> Middleware -> LanguageMiddleware.php

<?php
  
namespace App\Http\Middleware;
use Closure;
use App;
  
class LanguageMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session()->has('locale'))
        {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

Step 4 - Register Middleware

After modified the file we need to register in the kernel file. Let's see as below:

Open file app -> Http -> Kernel.php

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
    ....
  
    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            ....

            \App\Http\Middleware\LanguageMiddleware::class,
        ],
}

Step 5 - Create Controller

We will create new controller file to manage layout and change language dynamically, so please see the below command to generate file

php artisan make:controller LanguageController

Open file app -> Http -> Controllers -> LanguageController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App;
  
class LanguageController extends Controller
{

    public function index()
    {
        return view('index');
    }
  
    
    public function changeLang(Request $request)
    {
        App::setLocale($request->lang);
        session()->put('locale', $request->lang);
  
        return redirect()->back();
    }
}

Step 6 - Add Mapping Route

Now we will create two routes to show the webpage with select languages option and submit change language. So please see below routes.

Open file routes -> web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\LanguageController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::controller(LanguageController::class)->group(function()
{
    Route::get('/', 'index');
    Route::get('/lang', 'changeLang')->name('changeLang');
});

Step 7 - Create Blade File

Last step, we are going to create blade file to render HTML view with option change language.

Create file resources -> views -> index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Translate Language</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
  
        <div class="card">
          <div class="card-header">
            <h1>Google Translate Example - CamboTutorial.com</h1>
          </div>
          <div class="card-body">
                <div class="row">
                    <div class="col-md-2">
                        <strong>Select Language: </strong>
                    </div>
                    <div class="col-md-4">
                        <a href="{{ route('changeLang','en') }}" class="btn btn-primary">English</a>
                        <a href="{{ route('changeLang','kr') }}" class="btn btn-primary">Korean</a>
                        <a href="{{ route('changeLang','ch') }}" class="btn btn-primary">Chinese</a>
                    </div>
                </div>
                <h3>{{ GoogleTranslate::trans('Hello to CamboTutorial.com', app()->getLocale()) }}</h3>
          </div>
        </div>
    </div>
</body>
</html>

Step 8 - Run Laravel Server

Last we start run Laravel server with following command below

php artisan serve

Then go to your web browser, type the given URL localhost:8000/

Disclaimer: This package is developed for educational purposes only. Do not depend on this package as it may break anytime as it is based on crawling the Google Translate website. Consider buying Official Google Translate API for other types of usage.

You might also like...

 

Laravel  PHP  Laravel 9 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him