How to create multilingual translated routes in Laravel
Building a multilingual application often leads to decisions that compromise SEO or user experience. A common pattern involves using cookies or sessions to determine the language, but this creates duplicate content issues for search engines and friction for users switching languages. The goal is to derive the current language strictly from the URL structure. This approach ensures that /en/about is the canonical address for English content, while /kontakt remains the canonical Polish version without needing a prefix.
To achieve this in Laravel, you need a routing strategy where the language code is an optional segment at the beginning of your route group, and specific path segments are translated dynamically based on that context.
Defining the Route Structure
Assume your default language is pl (Polish), with English (en) and French (fr) as supported alternatives. You have three logical pages: Main Page, About, and Contact. The desired URL structure looks like this:
//kontakt/o-nas(About)/contact/en/kontakt/en/o-nas/fr/contact/fr/Ã -propos
In Laravel, you can define these routes by creating a single route group where the first segment is optional. This allows the application to handle requests for both prefixed and non-prefixed URLs under the same controller logic.
use Illuminate\Support\Facades\Route;
Route::group(['prefix => ''], function () {
// Default language routes (pl)
Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/kontakt', [ContactController::class, 'show'])->name('contact.pl');
Route::get('/o-nas', [AboutController::class, 'show'])->name('about.pl');
// English routes
Route::prefix('en')->group(function () {
Route::get('/', [HomeController::class, 'index'])->name('home.en');
Route::get('/contact', [ContactController::class, 'show'])->name('contact.en');
Route::get('/o-nas', [AboutController::class, 'show'])->name('about.en'); // Or translated path
});
// French routes
Route::prefix('fr')->group(function () {
Route::get('/', [HomeController::class, 'index'])->name('home.fr');
Route::get('/contact', [ContactController::class, 'show'])->name('contact.fr');
Route::get('/a-propos', [AboutController::class, 'show'])->name('about.fr');
});
});
While defining separate groups is explicit, it becomes unwieldy as the application grows. A more scalable approach involves a single route group that detects the prefix and adjusts the expected path translation accordingly. However, Laravel's default routing does not automatically translate path segments like /o-nas to /about. You must handle this translation logic either within the controller or via a dedicated service.
Implementing Dynamic Path Translation
The core challenge is ensuring that when a user visits /en/contact, the system understands they are requesting the English version of the contact page, but if they visit /contact, it assumes Polish. To keep this simple without complex middleware for every request, you can resolve the route name dynamically based on the detected language prefix.
Create a helper or service that maps the incoming path to a localized route name. For instance, if the URL starts with en/, the controller should be treated as serving English content. You can achieve this by checking the route parameters before executing the action:
public function show(Request $request)
{
$lang = $request->route()->uri === 'contact' ? 'pl' : ($request->route()->parameter('lang') ?? 'pl');
// Logic to determine which view or translation key to use based on $lang
$translationKey = "contact_page.{$lang}";
return view('pages.contact', [
'title' => __('views.pages.contact.' . ($lang === 'en' ? 'en_title' : 'pl_title'))
]);
}
This pattern requires your views to use Laravel's translation system (__('...')) and ensure that your language files contain keys for each supported locale. For example, in resources/lang/en/views/pages/contact.php, you would define the title, while resources/lang/pl/... defines the Polish version.
Handling the Root URL and Prefixes
A critical detail often overlooked is handling the root URL (/) alongside prefixed routes. In the example above, the root / serves as the home page for the default language. When a user visits /en, they are not requesting a specific resource but indicating the language context. You can treat /en and /fr as catch-all redirects or landing pages that set a temporary route parameter, though this might complicate SEO if you want distinct URLs for index pages.
A cleaner architectural decision is to ensure that every page has a direct translation in its URL path. This means instead of just /en, the user should navigate to /en/home or simply rely on the root / being the default language home. If you strictly require /en to exist as a valid route pointing to the home page, define it explicitly:
Route::prefix('en')->get('/', [HomeController::class, 'index'])->name('home.en');
This ensures that search engines index both /about and /en/about as distinct, canonical URLs.
Trade-offs and Considerations
The primary trade-off here is the complexity of maintaining multiple route definitions versus the flexibility of a single dynamic resolver. By separating routes by prefix, you gain clarity in your web.php file but increase the maintenance burden as new pages are added. Every new page requires three route definitions (one per language group).
For larger applications, consider generating these routes programmatically or using a package that abstracts this logic. However, for most projects, explicit route groups offer better performance and debugging capabilities compared to heavy regex-based translation within the router itself.
Remember that search engines prefer static URLs. Avoid relying on session-based language detection for routing; always let the URL dictate the content version. This ensures that when a user shares a link or bookmarks it, the correct localized content loads immediately without requiring them to change their browser settings first.