Home Laravel How to Use Google Translator in Laravel?

How to Use Google Translator in Laravel?

by Shahriar Sagor

Hello Dev, today now let’s see a tutorial on how to use google translator in laravel. Here i will show laravel google translate package. Now in this article, i will implement a how we can use google translate api in laravel. So It’s a very simple example of laravel google translate with multi language website. Just follow the below step for laravel multi language google translate.

So in this example, I will teach you step by step how to install the google translate in laravel and we don’t need to add any API key also. Just i will use stichoza/google-translate-php composer package. Here i will create a very simple website page with a language dropdown. then we can easily switch languages from there and the content i will display in the selected language. Without any further ado,

let’s see the below code example steps.

Step 1: Install Laravel 9

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel example-app
Step 2: Install Google Translate Package

Now in this step, we have to install stichoza/google-translate-php composer package and then need to add aliase on config file.

Let’s run the below command with the config file.

composer require stichoza/google-translate-php

let’s add the aliase on app.php file:

config/app.php

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

Now in this step, i will create two routes one for the displaying the dashboard page with a language drop-down and then another one for we can change language logic.

so add the below routes.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\LangController;
  
/*
|--------------------------------------------------------------------------
| 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::get('lang/home', [LangController::class, 'index']);
Route::get('lang/change', [LangController::class, 'change'])->name('changeLang');

Step 4: Create LangController Controller

Now at this point, now we have to create a new controller as LangController. Now in this controller i will manage layout and then change language dynamically logic, so put the below content in our controller file:

app/Http/Controllers/LangController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App;
  
class LangController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
    */
    public function index()
    {
        return view('lang');
    }
  
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
    */
    public function change(Request $request)
    {
        App::setLocale($request->lang);
        session()->put('locale', $request->lang);
  
        return redirect()->back();
    }
}

Step 5: Create View

Now in Last step, let’s create the lang.blade.php(resources/views/lang.blade.php) for layout and i will write design code here and also put following code:

resources/views/lang.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Create Multi Language Website in Laravel - CodingsPoint.com</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" 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 - CodingsPoint.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">
                        <select class="form-select changeLang">
                            <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 CodingsPoint.com', app()->getLocale()) }}</h3>
                <h3>{{ GoogleTranslate::trans('Hello World', app()->getLocale()) }}</h3>
          </div>
        </div>
      
    </div>
</body>
    
<script type="text/javascript">
    
    var url = "{{ route('changeLang') }}";
    
    $(".changeLang").change(function(){
        window.location.href = url + "?lang="+ $(this).val();
    });
    
</script>
</html>

Step 6: Create Middleware

Now in this file, we have to create one middleware on that will manage the dynamic language so that i can selected on the dropdown. so let’s create the middleware by using the bellow language.

php artisan make:middleware LanguageManager

Now you need to update the middleware file like below:

app/Http/Middleware/LanguageManager.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use App;
  
class LanguageManager
{
    /**
     * 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);
    }
}

Now i have to register it to the kernel file. So let’s add it as below:

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\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\LanguageManager::class,
        ],
  
        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
  
    ...

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like