DEV Community

Cover image for Laravel Localization: Multi-Language Website
Rafli Zocky
Rafli Zocky

Posted on • Originally published at Medium

Laravel Localization: Multi-Language Website

Auto-Translated (Content-Based)

Install Google Translate API PHP Package

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

Language Switcher (View)

<div class="flex items-center space-x-2">
    <a href="/lang/id"
        class="text-gray-200 hover:text-white {{ session('locale') === 'id' ? 'border-b-2 border-yellow-500' : '' }}">ID</a>
    <span class="text-gray-200">|</span>
    <a href="/lang/en"
        class="text-gray-200 hover:text-white {{ session('locale') === 'en' || !session('locale') ? 'border-b-2 border-yellow-500' : '' }}">EN</a>
</div>
Enter fullscreen mode Exit fullscreen mode

Route for Language Switching

Route::get('/lang/{lang}', function ($lang) {
    session(['locale' => $lang]);
    return back();
});
Enter fullscreen mode Exit fullscreen mode

Migration โ€” add columns to store translations:

Schema::table('abouts', function (Blueprint $table) {
    $table->string('title');
    $table->text('description');
    $table->json('title_translations')->after('title')->nullable();
    $table->json('description_translations')->after('description')->nullable();
});
Enter fullscreen mode Exit fullscreen mode

Model

protected $fillable = ['title', 'description', 'title_translations', 'description_translations', 'image'];

protected $casts = [
    'title_translations' => 'array',
    'description_translations' => 'array',
];

public function getTranslatedTitle()
{
    $locale = session('locale', 'id');
    return $this->title_translations[$locale] ?? $this->title;
}

public function getTranslatedDescription()
{
    $locale = session('locale', 'id');
    return $this->description_translations[$locale] ?? $this->description;
}
Enter fullscreen mode Exit fullscreen mode

Trait for Auto Translation (app/Traits/Translatable.php)

namespace App\Traits;

use Stichoza\GoogleTranslate\GoogleTranslate;

trait Translatable {
    public function autoTranslate($text) {
        $translator = new GoogleTranslate();
        return [
            'en' => $translator->setTarget('en')->translate($text),
            'id' => $translator->setTarget('id')->translate($text),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Controller (Store & Update)

use App\Traits\Translatable;

class AboutController extends Controller
{
    use Translatable;

    public function store(Request $request)
    {
        $validatedData['title_translations'] = $this->autoTranslate($validatedData['title']);
        $validatedData['description_translations'] = $this->autoTranslate($validatedData['description']);
        About::create($validatedData);
    }

    public function update(Request $request, string $id)
    {
        if ($request->has('title')) {
            $validatedData['title_translations'] = $this->autoTranslate($request->title);
        }
        if ($request->has('description')) {
            $validatedData['description_translations'] = $this->autoTranslate($request->description);
        }
        $about->update($validatedData);
    }
}
Enter fullscreen mode Exit fullscreen mode

View

{{ $about->getTranslatedTitle() }}
{{ $about->getTranslatedDescription() }}
Enter fullscreen mode Exit fullscreen mode

Static Translations (Manual Inline)

๐Ÿ“Œ Normally you'd use resources/lang/{locale} files, but here's a quick inline method.

Route

Route::get('/lang/{lang}', function ($lang) {
    if (!in_array($lang, ['en', 'id'])) {
        $lang = 'id';
    }
    session(['locale' => $lang]);
    app()->setLocale($lang);
    return back();
});
Enter fullscreen mode Exit fullscreen mode

View

@php
$newsTranslations = [
    'section_title' => [
        'id' => 'Berita Pertambangan Nasional',
        'en' => 'National Mining News',
    ],
];
$locale = session('locale', 'id');
@endphp

<h2 class="text-3xl md:text-4xl font-bold text-gray-800 mb-3">
    {{ $newsTranslations['section_title'][$locale] }}
</h2>
Enter fullscreen mode Exit fullscreen mode

That's all. You've now got basic multilingual support for both dynamic (admin input) and static (inline text) content in Laravel.


Need help building your app?
I'm available for freelance web & Android development โ€” raflizocky.netlify.app

โ˜• Support my writing: paypal.me/raflizocky ยท saweria.co/raflizocky

Top comments (0)