How to Add Google Translate in Laravel

Hello Artisans, today I'll show you how to add google translate to your Laravel application. Google translate gives us a wide variety of languages for translations. We'll use stichoza/google-translate-php package to accomplish our result So, let's see how we can easily integrate google translate into our Laravel application.

Note: Tested on Laravel 9.19

Table of Contents

  1. Install and configure stichoza/google-translate-php package
  2. Create and Configure Middleware
  3. Create and Setup Controller
  4. Create Route
  5. Setup View
  6. Output

Install and configure stichoza/google-translate-php package

At first, we've to install stichoza/google-translate-php package. So, fire the below command to install

composer require stichoza/google-translate-php

Now we've to register its aliases in app.php. Put the below code inside aliases array like below.

config/app.php
'aliases' => Facade::defaultAliases()->merge([
        'GoogleTranslate' => Stichoza\GoogleTranslate\GoogleTranslate::class
    ])->toArray(),

Create and Configure Middleware

Now we'll create a middleware where we'll set our selected language as the app's default locale. Now fire the below command in the terminal.

php artisan make:middleware ChangeLocale

It'll create a file under app\Http\Middleware called ChangeLocale.php. Now open the file and replace it with the below codes.

app/Http/Middleware/ChangeLocale.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ChangeLocale
{
    public function handle(Request $request, Closure $next)
    {
        if (session()->has('locale')) {
            app()->setLocale(session()->get('locale'));
        }

        return $next($request);
    }
}

Now we need to register in $middlewareGroups array. See the below source code,

app/Http/Kernel.php
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\ChangeLocale::class
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

Create and Setup Controller

Now we'll create a controller where we'll set our selected language in session. Now fire the below command in the terminal to create a controller.

php artisan make:controller GoogleTranslateController

It'll create a file under app\Http\Controllers called GoogleTranslateController.php. Now open the file and replace it with the below codes.

app/Http/Controllers/GoogleTranslateController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class GoogleTranslateController extends Controller
{
    public function change(Request $request): \Illuminate\Http\RedirectResponse
    {
        session()->put('locale', $request->lang);

        return back();
    }
}

Create Route

Now, we need to create a route so that when a user selects a language, it'll be redirected to our controller. So put this below route in web.php

routes/web.php
Route::get('lang/change', [GoogleTranslateController::class, 'change'])->name('change.lang');

Setup View

Now we'll update our default blade file called welcome.blade.php which is come by default. Now open the file and replace it with the below codes.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Google Translate Package Example - shouts.dev</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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <div class="card">
        <div class="card-header">
            <h1>Laravel Google Translate Example - shouts.dev</h1>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-2">
                    <strong>Select Language: </strong>
                </div>
                <div class="col-md-4">
                    <select class="form-select change_lang">
                        <option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
                        <option value="fr" {{ session()->get('locale') == 'fr' ? 'selected' : '' }}>France</option>
                        <option value="es" {{ session()->get('locale') == 'es' ? 'selected' : '' }}>Spanish</option>
                    </select>
                </div>
            </div>
            <h3>{{ GoogleTranslate::trans('Welcome to shouts.dev', app()->getLocale()) }}</h3>
            <h3>{{ GoogleTranslate::trans('Hello World', app()->getLocale()) }}</h3>
        </div>
    </div>
</div>
</body>

<script>
    var url = "{{ route('change.lang') }}";
    $(document).ready(function (){
        $(document).on('change','.change_lang',function (){
            window.location.href = url   "?lang="  $(this).val();
        });
    });
</script>
</html>

Output

And finally, we're ready with our setup. It's time to check our output. Now go to http://127.0.0.1:8000, If everything goes well (hope so) we can see the below output.

That's it for today. I hope you've enjoyed this tutorial. You can also download this tutorial from GitHub. Thanks for reading. ๐Ÿ™‚