Introduction
Building a multilingual system for your Laravel SaaS is more than just using translation files. It involves automatic language detection, seamless translation of user-generated content, and efficient localization strategies. This guide explores how to achieve a robust solution using Inertia and Vue.
Challenges in SaaS i18n
Typical SaaS applications often claim to support internationalization (i18n) but fall short when it comes to real-world needs:
- User Language Detection: How do you determine a user's preferred language on their first visit?
- Preference Persistence: How do you maintain this preference across different sessions and devices?
- Efficient Translation Delivery: How can you pass multiple translation strings to a JavaScript frontend without burdening your API?
- User Content Translation: How do you handle translations for user-generated content?
System Architecture Overview
The system architecture starts with the SetLocale Middleware, which is responsible for language detection and setting:
- User Locale: Retrieved from the database if the user is authenticated.
- Session Locale: Checked if available.
- Browser Language: Extracted from the browser's Accept-Language header.
- IP Geolocation: Utilized if other methods fail, using services like ip-api.com.
- Default Locale: Fallback to a predefined language if all else fails.
Backend Implementation
Locale Detection Middleware
The SetLocale Middleware is a core component that runs on every request:
public function handle(Request $request, Closure $next)
{
$locale = $this->determineLocale($request);
app()->setLocale($locale);
return $next($request);
}
Language Switching
A simple controller allows users to manually switch languages:
public function languageSwitch($locale = 'en')
{
if (array_key_exists($locale, config('app.available_languages'))) {
app()->setLocale($locale);
Session::put('locale', $locale);
if (auth()->check()) {
auth()->user()->update(['locale' => $locale]);
}
Cookie::queue('locale', $locale, 525600); // 1 year
}
return redirect()->back();
}
Frontend Integration with Vue
Inertia Prop Sharing
The translations are shared through Inertia props, ensuring they are available without additional API calls:
public function share(Request $request): array
{
return [
'locale' => fn () => App::getLocale(),
'translations' => $this->loadTranslations(),
];
}
Vue i18n Setup
Vue is set up to use the translations, allowing for simple language switching:
import { createI18n } from 'vue-i18n';
const i18n = createI18n({
legacy: false,
locale: pageProps.locale || 'en',
messages: { [locale]: pageProps.translations || {} },
});
Conclusion
Developing a comprehensive multilanguage system for Laravel SaaS involves more than basic translation functions. By combining Inertia and Vue, you can create a seamless multilingual experience that meets the needs of modern SaaS applications. LaraFoundry offers a straightforward yet powerful framework to achieve this.