
Laralang for Laravel Rust
Introduction
Laralang lets you create localized routes for different languages. You declare a route once and the crate registers a real route per language, each with its own path, so a multilingual application keeps one URL per page per language.
It is the port of Laralang, the PHP package, to Laravel Rust. It targets Laravel Rust 0.1, which is in beta, and its API follows the framework's changes until 1.0. The behaviour, the names and this document follow the PHP package. Where Laravel Rust has no equivalent, the section says so, and the differences are collected at the end.
Features
- Declare a route once and get a real route per language, each with its own path.
laralang::route("dashboard", ())resolves to the current language, and"es.dashboard"targets a specific one. Laravel Rust 0.1 has no named routes, so Laralang brings the registry that names them.- Localized resources, with the resource name and the
createandeditsegments translated. laralang::alternates()returns the current page in every language, ready for language switchers,hreflangtags and multi locale sitemaps.laralang::route_is(&["dashboard"])matches any language, so navigation active states keep working.- A localized fallback that rescues a URL living under another language instead of returning a 404.
- The language of the URL, the session or the browser, with one middleware per strategy, on top of laralocale.
- The route registry for the frontend, in Ziggy's shape, to share through Inertia.
route(),laralang_alternates()androute_is()in MiniJinja views.
Requirements
- Laravel Rust
0.1 - laralocale, which holds the current locale. Laralang sets it from the URL prefix and reads it to build URLs, and keeps no locale of its own.
Installation
Register both service providers in src/app.rs, laralocale first, and list the languages you support. with_detection() makes laralocale read the stored choice and Accept-Language for the pages that have no language in their URL:
use LaralangServiceProvider;
use ;
use *;
Add the Laralang provider before the route files that use it. It registers its own configuration, the
registry, the view functions and, when fallback is on, the localized fallback.
Getting started
This will generate routes for /dashboard in English and /es/panel in Spanish:
use ;
use Router;
You can add any middleware as usual:
get
.middleware
.name;
The routes are registered when the statement ends. The handler is shared by every language, so it must be
Clone, which functions and closures that capture nothing are.
Configuration
LaralangConfig is the configuration section, which you set in src/app.rs with with_config, and
config/locales.php of the PHP package is its counterpart. The keys have the same names and defaults:
| Key | Default | |
|---|---|---|
locales |
[] |
The languages that get routes. Empty means the supported locales of laralocale |
prefixes |
{} |
The URL prefix of each locale |
fallback |
false |
The localized fallback |
redirect_max_age |
86400 |
The max-age of permanent redirects, in seconds |
Supported locales
In Laravel the default locale is config('app.locale'). Laravel Rust has no such thing, so it is the
locale setting of laralocale's LocaleConfig, read from APP_LOCALE, and the supported languages are
its supported list:
config..supported = .map.to_vec;
LaralangConfig::locales exists for the PHP key's sake: set it only when the languages with routes are
not the ones laralocale detects.
Locale prefixes
prefixes gives each locale a custom URL prefix. You do not need to list them all: by default the locale
code is the prefix, except for the default language.
let laralang = config.;
laralang.prefixes.insert; // /es
laralang.prefixes.insert; // /francais
The default language never carries a prefix. It is the locale of laralocale, not the first entry
of supported, so with APP_LOCALE=es it is Spanish that lives at the root and English that gets
prefixed. SetRouteLocale enforces it too: a first segment matching the default locale is redirected
with a 301 to the same URL without it, so there is a single canonical URL per page.
The rule is short: a value is the literal prefix, and without one the locale code is used. A missing key and an empty string both count as no value.
| Value | Default language | Any other language |
|---|---|---|
key missing or "" |
no prefix | its own code, /fr |
"anything" |
that literal, /anything |
that literal, /anything |
Only the default language can live at the root, so two locales can never end up sharing the same URLs.
Prefixing every language
By default the default language lives at the root, and a URL that repeats its prefix is redirected there
with a 301, so each page has a single canonical URL.
Give the default language a prefix of its own and that stops: every language gets one, and nothing lives at the root.
laralang.prefixes.insert; // /en/about
laralang.prefixes.insert; // /es/sobre-nosotros
Since no route is registered at / any more, turn the localized fallback on so the root has somewhere
to go:
laralang.fallback = true;
It sends the visitor to their own language, taken from what laralocale detected (their stored choice, then
Accept-Language) and falling back to the default. That redirect is a 302 with
Vary: Accept-Language, never a 301, because the destination depends on who is asking and a permanent
one would be cached and pin a single language for everyone behind it.
Decide the prefixes before going live
Everything else the crate redirects is a 301, which is the right status because the destination depends
only on the path. But permanent means permanent: browsers and CDNs cache it, and a cached 301 is never
re-checked.
Those redirects are computed from prefixes and the order of the locales, so changing either after the
site is public leaves old clients following redirects to URLs that no longer exist. The painful case is
prefixing every language on a site that served English at the root: /en/about has been answering 301
to /about for months, and once /en/about is canonical a returning visitor's browser applies the cached
redirect without asking and lands on /about, which no longer exists. With the fallback on it is worse
than a 404: /about is rescued back to /en/about, and the browser gives up with a redirect loop.
Treat the shape of your URLs as a decision to make before launch. If you have to change it anyway, consider turning the fallback off during the transition, so a visitor with a stale redirect gets a plain 404 instead of a loop. What you can bound is how long that lasts.
Redirect cache lifetime
laralang.redirect_max_age = 86_400; // seconds
Sets the Cache-Control: max-age of the permanent redirects, the one that strips a redundant default
locale prefix and the fallback rescue. A day is a good default while your URLs are still moving. Raise it
once they are settled. The 302 at the root is never cached: it carries no-store.
How to register localized routes
Use LocalizedRoute::get(), post(), put(), patch(), delete(), options(), any() or match(),
the way you would use the router's own methods. The router is the first argument, because Laravel Rust has
no global Route facade:
use ;
get.name;
post
.name;
Assuming en is your default locale, those two calls register four routes:
| Method | URL | Route name |
|---|---|---|
| GET | /profile |
en.profile |
| GET | /es/perfil |
es.profile |
| POST | /update-profile |
en.update-profile |
| POST | /es/actualizar-perfil |
es.update-profile |
This is how it works:
- The first parameter is the URI, and it is the one used for any locale listed without a translation.
- The locales are written with
locales!, as PHP writes them. A bare"en"reuses the first parameter, and"es" => "perfil"gives that locale its own path. - The last parameter is the handler.
- The default locale gets no prefix, and every other locale is prefixed with its code unless you configure a different prefix.
Matching several methods
match() takes the list of HTTP methods, and any() registers the route for all of them:
r#match
.name;
any.name;
any() still registers one route per locale, and each of them answers every verb Laravel Rust's
Router::any does. LocalizedRoute::on(route, &[Method::GET], ..) takes Method values, as Router::on
does.
Chaining
After the registration call, chain what you would chain on a route:
| Method | |
|---|---|
.name("dashboard") |
Names the routes en.dashboard, es.dashboard |
.middleware(m) |
Adds middleware to every language's route |
.with_head(head) |
Merges head metadata into every language's route |
.without_middleware::<M>() |
Opts every language's route out of a middleware |
.configure(|route| ..) |
Anything else, applied to each route |
Inside a route group
The locale prefix goes first, before any prefix coming from the group. Router::prefix cannot do that,
because it puts its prefix in front of whatever you register inside it, so Laralang has a group of its own:
prefix.group;
| URL | Route name |
|---|---|
/admin/dashboard |
en.admin.dashboard |
/fr/admin/dashboard |
fr.admin.dashboard |
/es/admin/panel |
es.admin.dashboard |
Note that fr reuses dashboard because it was listed without a translation, while es uses its own
panel. Group middleware keeps working as usual, with route.middleware(..).group(..). Routes you
register with route.get(..) inside a Laralang group are not prefixed by it.
If you wrap localized routes in Router::prefix("zone") anyway, the router's prefix comes first,
/zone/es/panel, and the registry records that, so route() stays right.
Localized resources
LocalizedResource registers a resource once per locale. PHP takes a controller class, and Laravel Rust
has handler functions, so a resource is the set of handlers you give it:
use ;
make;
| URL | Route name |
|---|---|
/photos |
en.photos.index |
/photos/create |
en.photos.create |
/photos/{photo} |
en.photos.show |
/es/fotos |
es.photos.index |
/es/fotos/create |
es.photos.create |
/es/fotos/{photo} |
es.photos.show |
Two things are deliberate here. The route names use the base resource name in every locale, so
route("photos.index") resolves to the current language like any other localized route. And the route
parameter is {photo} in every locale, derived from the base name too, so a single show handler keeps
working no matter which language resolved the URL.
Translating create and edit
Give a locale its own create and edit segments in its definition:
make;
| URL | Route name |
|---|---|
/photos/create |
en.photos.create |
/photos/{photo}/edit |
en.photos.edit |
/es/fotos/crear |
es.photos.create |
/es/fotos/{photo}/editar |
es.photos.edit |
Without them those two segments stay in English for every locale.
API resources
LocalizedResource::api() registers the same resource without the create and edit routes. Localizing
an API is rarely what you want, since machines consume its URLs and the language is usually negotiated
with Accept-Language.
Chaining options
make
.only
.middleware;
only(), except() and middleware() apply to every locale at once, as do middleware_for() and
parameter(). Action is laravel::routing::Action.
The LocalizedRoute bridge
LocalizedRoute::resource() and LocalizedRoute::api_resource() do exactly the same, delegating to
LocalizedResource.
Generating URLs
Laravel Rust 0.1 generates URLs from a route's handler, which cannot tell the languages of one localized
route apart, since they share a handler and differ in their URIs. laralang::route() builds them from
the names instead:
route?; // English
route?; // Spanish
route?; // the current language
route("dashboard") is the route named dashboard of the current locale, which is laralocale's
locale(). A name that starts with one of your locales is used as it is.
Parameters are pairs, a Params value or positional values. A parameter the URI
does not name becomes the query string:
route?; // /es/servicios/hola
route?; // in the current language
route?; // /services?page=2
route_with?; // "/services", relative
has("dashboard") says whether a route has that name. An unknown name, or a missing parameter, is a 500
error.
Using localized routes in views
route() is a MiniJinja function with the same name, so {{ route('dashboard') }} is the URL in the
language of the request:
Dashboard
En español
Hola
Hola
Hola
Relative
It also knows the names of Laravel Rust's own route() (posts::show), which it hands over when the name
is not a localized one, so your existing templates keep working.
Ziggy and the frontend
Laravel Rust has no Ziggy. laralang::ziggy() returns the route registry in the shape of Ziggy 2's
payload, so Ziggy's JavaScript route() can read it, and share it through Inertia:
import from 'ziggy-js';
;
As with the PHP package's Ziggy integration, the routes of the current locale are also published under
their unprefixed name, so route('dashboard') behaves in JavaScript as it does in Rust, while
route('es.dashboard') keeps working too. A name that already exists is never replaced by an alias.
Generating alternate URLs
For language switchers, hreflang tags, multi-locale sitemaps and canonical URL switching,
laralang::alternates() returns the current route in every configured locale, without any locale
swapping:
let alternates = alternates?;
// en -> https://example.com/services
// es -> https://example.com/es/servicios
// ca -> https://example.com/ca/serveis
alternates.get; // Some("https://example.com/es/servicios")
for in alternates.iter
hreflang tags
Laravel Rust has Head::alternate, so the tags need no loop: merge them into the page's head and the
head() of your layout prints them.
async
That is laravel::head::merge(laralang::alternates_head()?). alternates_head() returns the Head if you
want to add to it first. The result:
A language switcher in a template:
{% for locale, url in laralang_alternates() | items %}
{{ locale | upper }}
{% endfor %}
Parameters
The PHP signature alternates(array $params = [], bool $absolute = true) is two functions:
alternates?; // the current parameters, absolute URLs
alternates_with?; // overridden parameters, relative paths
The parameters default to the current route's, so a dynamic segment such as {slug} is carried into every
locale's URL. In a template, laralang_alternates(params, absolute) takes the same two arguments.
Behaviour notes:
- If a route is declared in a subset of locales, the result only contains the locales that have it. No dead links.
- Outside a localized route, or on a route with no name, it is empty.
Using route_is() with localized routes
route_is() ports the routeIs() override. Because localized routes are named en.services,
es.services and fr.services, a plain route_is(&["services"]) matches all of them. The rules:
- A plain pattern matches if the current route name matches it literally or if it matches
{anyLocale}.{pattern}. - A locale-prefixed pattern, such as
es.services, only matches when the prefix is the current locale and the current route name matches literally. *matches anything, soservices*matcheses.services.showtoo.
// On the Spanish variant of /servicios:
route_is; // true
route_is; // true
route_is; // false
route_is; // true on es.services.show, fr.services.create, ...
In a template, {% if route_is('services') %}active{% endif %}. It is false outside a localized route.
Localized fallback
A URL is often shared or linked without its locale prefix, or with the wrong one. /servicios reaches an
application that is running in English, /es/services reaches one that expects the Spanish path. Both are a
404 by default, and both are a page you already have.
Turn the rescue on in the configuration:
config..fallback = true;
From then on, a URL that matches no route but does exist under another locale is redirected there with a
301:
| Requested | Rescued to |
|---|---|
/servicios |
/es/servicios |
/fr/servicios |
/es/servicios |
/es/services |
/services |
/propiedad/piso-centro |
/es/propiedad/piso-centro |
Route parameters are honoured and the query string travels along untouched. Anything that cannot be rescued
keeps returning the 404 it deserves, and a request that is not a GET or a HEAD is never rescued.
Which locale wins
Locales are tried with the default one first, then in the order of the configured locales. That way the
destination depends only on the path and never on the visitor, which is what makes a permanent redirect
safe: a 301 gets cached by browsers and CDNs, so a destination that changed with the visitor's language
would pin one language for everyone behind the cache.
If your application has its own fallback
A later fallback replaces an earlier one, so your own fallback takes the place of Laralang's. Leave
fallback off and call the rescue from yours, which answers with the 404 when there is nothing to rescue:
async
Or register it yourself with LocalizedRoute::fallback(route).
The rescue only knows the routes registered through Laralang, since Laravel Rust 0.1 offers no way to ask the router whether a path matches.
Middleware
Laralang comes with the locale middlewares of the PHP package, which you attach like any other, and which
set the locale with laralocale::with_locale. Reading the language from the session, a cookie or the
browser is laralocale's DetectLocale, which LaralocaleServiceProvider::new().with_detection() puts in
the web group, so most applications need none of these for plain routes. An application that only wants
the browser's header can instead call laralocale::set_locale(request.preferred_locale()) in a middleware
of its own.
All of them are idempotent: the first one to run resolves the locale, and the rest only pass the request on.
Every localized route carries its own SetRouteLocale, so the language of the URL needs nothing from you.
SetRouteLocale
Detects the locale from the URL prefix. Localized routes have it already, and SetRouteLocale::new() reads
the first segment of any other route:
route.middleware.group;
Visiting /es/panel sets the locale to es before the handler runs, so everything that asks laralocale, the
views included, is in Spanish. It stores the locale in the session under laralocale's detect.session key, so
a plain page the visitor opens next stays in the language they were reading.
SetSessionLocale
Applies the locale stored in the session, and the default one when there is none. Useful for internal routes, such as admin panels, where the language is chosen once and stored.
SetBrowserLocale
Reads the locale from Accept-Language only if the session has none, and stores it in the session. Good for
public routes to detect a first-time visitor's language.
SetSmartLocale
The universal one: the route prefix first, then the session or the browser.
route.middleware.group;
/es/contacto runs in Spanish because of the prefix, and /dashboard, which has no prefix to read, falls
back to the session and then to the browser language.
Differences from the PHP package
- The router is an argument.
LocalizedRoute::get(route, "uri", locales, handler), where PHP hasLocalizedRoute::get('uri', locales, action). Laravel Rust has noRoutefacade.LocalizedRoute::matchis writtenr#match, becausematchis a keyword, and takes method names as strings. - Locales are
locales!["en", "es" => "panel"], a macro that reads like PHP's['en', 'es' => 'panel']. A resource locale with translated segments is"es" => ("fotos", "create" => "crear", "edit" => "editar"). - Handlers, not controllers. A resource takes a
ResourceHandlersset, andLocalizedResource::makeneeds the router too. Laravel Rust'sResourcecannot be used, because it fixes thecreateandeditsegments.names(),shallow()andscoped()are not ported, and a resource name is a single segment. - Registration happens when the statement ends, as with Laravel Rust's own
ResourceRoutes. Chain.name()and the rest in the same statement. - The registry is the package's. Laravel Rust 0.1 has no named routes, so
route(),alternates()androute_is()read the routes Laralang registered, and only those. A route registered withroute.get()has no name, soalternates()is empty on it, where PHP answers[current_locale => current_url]. Router::prefixcannot put the locale first. The router offers no way to read or move its prefix, soLocalizedRoute::prefix("admin").group(route, ..)replacesRoute::prefix('admin')->group()for localized routes. Nested in aRouter::prefix, the router's prefix comes first, and the registry records it.alternates()is two functions,alternates()andalternates_with(params, absolute), since Rust has no default arguments.laralang_alternates()is the same.- URL parameters are values you pass,
[("slug", "hola")],Params, orParams::positional([..]). A model is not filled with its key: pass the value. - Config. The PHP file
config/locales.phpisLaralangConfig.localesis empty by default and means laralocale'ssupported, andapp.localeis laralocale'slocale. A prefix is aHashMap<String, String>, with nonull: a missing key is the same thing. - Middleware. Laravel Rust has no global
App::setLocale, so the middleware useslaralocale::with_locale. TheX-Livewireand ajax rule ofSetRouteLocaleis dropped, since an Inertia visit is an ajax request that should follow its URL.ValidateLocalizedSignatureand thesigned_localizedalias are not ported: Laravel Rust signs URLs by handler, not by name. - The fallback answers
404, not405, to aPOST, and only rescues the routes Laralang registered. A later fallback replaces an earlier one, so there is no ordering to manage. - Ziggy is
laralang::ziggy(), a payload for Inertia, and Ziggy's own JavaScript. The Blade generator is not ported. - Views.
@routesand Blade are MiniJinja:route(),laralang_alternates()androute_is()are functions.route()keeps Laravel Rust's ownroute("posts::show")working.
Sponsors
Laralang for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:
Author
Created by Edu Lazaro
License
Laralang for Laravel Rust is open-sourced software licensed under the MIT license.