Autodetect and switch page language in Laravel 9 + Vue 3 + Inertia.js

Let’s implement locale detection by using browser language, a way to manually switch it and to persist it in the session storage.

Serdar Cevher
2 min readMay 26, 2022
  1. Add the “locales” array to your config/app.php after the ‘locale’ => ‘en’ line to indicate available languages (English and Turkish in my case):
...
'locale' => 'en',
'locales' => ['en', 'tr'],

2. Create the App/Http/Middleware/Localization.php with the following content:

3. Add this middleware to the $middlewareGroups array in the App/Http/Kernel.php:

protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\HandleInertiaRequests::class,
\App\Http\Middleware\Localization::class,
],

4. Add the following lines into your routes/web.php to let the user manually switch the locale:

5. Ensure that you share your app’s locale with the frontend in your app/Providers/AppServiceProvider.php:
(this can also be handled in HandleInertiaRequests middleware if you prefer)

public function boot()
{
Inertia::share([
'locale' => function () {
return app()->getLocale();
},
...
}

6. Finally, implement the front end switch mechanism as you desire. In my case, I hardcoded language names as I only use two of them, but you may want to put an additional config array and to iterate it for a more systematic approach.

<Link :href="route('locale.set', $page.props.locale == 'tr' ? 'en' : 'tr')">
{{ $page.props.locale == 'tr' ? 'English' : 'Türkçe' }}
</Link>

You’re ready to go now.

— -
Loading and using translations is not covered within this article. You can have a look at this link for further information: https://devonmather.dev/posts/localizing-a-laravel-app-using-vuejs-and-inertiajs-without-any-dependencies

--

--

Serdar Cevher

Developer of web & mobile apps | Co-founder: Auglinn, Off2Class | Founder: SmarDish, tarifmotoru.com, valizim.com | Ex columnist @PCnetDergisi