laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation

Laralang for Laravel Rust

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 create and edit segments translated.
  • laralang::alternates() returns the current page in every language, ready for language switchers, hreflang tags 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() and route_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

cargo add laralang laralocale

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 laralang::LaralangServiceProvider;
use laralocale::{LaralocaleServiceProvider, LocaleConfig};
use laravel::prelude::*;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        .with_providers(|providers| {
            providers.add(LaralocaleServiceProvider::new().with_detection());
            providers.add(LaralangServiceProvider::new());
        })
        .with_config(|config, _| {
            config.section_mut::<LocaleConfig>().supported = ["en", "es", "fr"].map(str::to_owned).to_vec();
        })
}

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 laralang::{LocalizedRoute, locales};
use laravel::routing::Router;

pub fn routes(route: &mut Router) {
    LocalizedRoute::get(route, "dashboard", locales!["en", "es" => "panel"], dashboard).name("dashboard");
}

You can add any middleware as usual:

LocalizedRoute::get(route, "dashboard", locales!["en", "es" => "panel"], dashboard)
    .middleware(Authenticate)
    .name("dashboard");

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.section_mut::<LocaleConfig>().supported = ["en", "es", "fr"].map(str::to_owned).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.section_mut::<LaralangConfig>();

laralang.prefixes.insert("es".to_owned(), "es".to_owned());   // /es
laralang.prefixes.insert("fr".to_owned(), "francais".to_owned());   // /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".to_owned(), "en".to_owned());   // /en/about
laralang.prefixes.insert("es".to_owned(), "es".to_owned());   // /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 laralang::{LocalizedRoute, locales};

LocalizedRoute::get(route, "profile", locales!["en", "es" => "perfil"], profile::show).name("profile");
LocalizedRoute::post(route, "update-profile", locales!["en", "es" => "actualizar-perfil"], profile::update)
    .name("update-profile");

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:

LocalizedRoute::r#match(route, &["PUT", "PATCH"], "profile", locales!["en", "es" => "perfil"], profile::update)
    .name("profile.update");

LocalizedRoute::any(route, "webhook", locales!["en", "es" => "gancho"], webhook::handle).name("webhook");

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:

LocalizedRoute::prefix("admin").group(route, |route| {
    LocalizedRoute::get(route, "dashboard", locales!["en", "fr", "es" => "panel"], admin::dashboard)
        .name("admin.dashboard");
});
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 laralang::{LocalizedResource, ResourceHandlers, locales};

LocalizedResource::make(
    route,
    "photos",
    locales!["en", "es" => "fotos"],
    ResourceHandlers::new()
        .index(photos::index)
        .create(photos::create)
        .store(photos::store)
        .show(photos::show),
);
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:

LocalizedResource::make(
    route,
    "photos",
    locales!["en", "es" => ("fotos", "create" => "crear", "edit" => "editar")],
    handlers,
);
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

LocalizedResource::make(route, "photos", locales!["en", "es" => "fotos"], handlers)
    .only([Action::Index, Action::Show])
    .middleware(Authenticate);

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:

laralang::route("en.dashboard", ())?;   // English
laralang::route("es.dashboard", ())?;   // Spanish
laralang::route("dashboard", ())?;      // 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:

laralang::route("es.services.show", [("slug", "hola")])?;          // /es/servicios/hola
laralang::route("services.show", Params::positional(["hola"]))?;   // in the current language
laralang::route("services", [("page", 2)])?;                       // /services?page=2
laralang::route_with("services", (), false)?;                      // "/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:

<a href="{{ route('dashboard') }}">Dashboard</a>
<a href="{{ route('es.dashboard') }}">En español</a>
<a href="{{ route('services.show', slug='hola') }}">Hola</a>
<a href="{{ route('services.show', {'slug': 'hola'}) }}">Hola</a>
<a href="{{ route('services.show', 'hola') }}">Hola</a>
<a href="{{ route('services', {}, false) }}">Relative</a>

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:

impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, _request: &Request) -> laravel::Result<Props> {
        Ok(props! { ziggy => laralang::ziggy() })
    }
}
import { route } from 'ziggy-js';

route('dashboard', undefined, undefined, page.props.ziggy);

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 = laralang::alternates()?;
// en -> https://example.com/services
// es -> https://example.com/es/servicios
// ca -> https://example.com/ca/serveis

alternates.get("es");                 // Some("https://example.com/es/servicios")
for (locale, url) 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 fn show() -> laravel::Result<View> {
    laralang::merge_alternates()?;

    Ok(view("services.show", ()))
}

That is laravel::head::merge(laralang::alternates_head()?). alternates_head() returns the Head if you want to add to it first. The result:

<link rel="alternate" href="https://example.com/services" hreflang="en">
<link rel="alternate" href="https://example.com/es/servicios" hreflang="es">

A language switcher in a template:

<ul>
{% for locale, url in laralang_alternates() | items %}
    <li><a href="{{ url }}" hreflang="{{ locale }}">{{ locale | upper }}</a></li>
{% endfor %}
</ul>

Parameters

The PHP signature alternates(array $params = [], bool $absolute = true) is two functions:

laralang::alternates()?;                                     // the current parameters, absolute URLs
laralang::alternates_with([("slug", "custom")], false)?;     // 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, so services* matches es.services.show too.
// On the Spanish variant of /servicios:
laralang::route_is(&["services"]);       // true
laralang::route_is(&["es.services"]);    // true
laralang::route_is(&["fr.services"]);    // false
laralang::route_is(&["services*"]);      // 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.section_mut::<LaralangConfig>().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 fn not_found(request: Request) -> laravel::Result<Response> {
    laralang::localized_fallback(request).await
}

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(SetRouteLocale::new()).group(|route| {
    route.get("/es/dashboard", dashboard);
});

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(SetSmartLocale).group(|route| {
    LocalizedRoute::get(route, "contact", locales!["en", "es" => "contacto"], contact::show).name("contact");
    route.get("/dashboard", dashboard);
});

/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 has LocalizedRoute::get('uri', locales, action). Laravel Rust has no Route facade. LocalizedRoute::match is written r#match, because match is 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 ResourceHandlers set, and LocalizedResource::make needs the router too. Laravel Rust's Resource cannot be used, because it fixes the create and edit segments. names(), shallow() and scoped() 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() and route_is() read the routes Laralang registered, and only those. A route registered with route.get() has no name, so alternates() is empty on it, where PHP answers [current_locale => current_url].
  • Router::prefix cannot put the locale first. The router offers no way to read or move its prefix, so LocalizedRoute::prefix("admin").group(route, ..) replaces Route::prefix('admin')->group() for localized routes. Nested in a Router::prefix, the router's prefix comes first, and the registry records it.
  • alternates() is two functions, alternates() and alternates_with(params, absolute), since Rust has no default arguments. laralang_alternates() is the same.
  • URL parameters are values you pass, [("slug", "hola")], Params, or Params::positional([..]). A model is not filled with its key: pass the value.
  • Config. The PHP file config/locales.php is LaralangConfig. locales is empty by default and means laralocale's supported, and app.locale is laralocale's locale. A prefix is a HashMap<String, String>, with no null: a missing key is the same thing.
  • Middleware. Laravel Rust has no global App::setLocale, so the middleware uses laralocale::with_locale. The X-Livewire and ajax rule of SetRouteLocale is dropped, since an Inertia visit is an ajax request that should follow its URL. ValidateLocalizedSignature and the signed_localized alias are not ported: Laravel Rust signs URLs by handler, not by name.
  • The fallback answers 404, not 405, to a POST, 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. @routes and Blade are MiniJinja: route(), laralang_alternates() and route_is() are functions. route() keeps Laravel Rust's own route("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.