Open source December 2026
Laralang Rust

Laralang Rust

Laralang Rust

Laralang Rust is the URL half of a multilingual Laravel Rust app: 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 does not touch the text on the page, which is a separate concern.

Written against version 0.1, which targets Laravel Rust 0.1 (in beta). Its API follows the framework's changes until 1.0.

This is the port of Laralang, the PHP package, and its behaviour and names follow it. It builds on Laralocale for Laravel Rust, which holds the current locale. The crate is on crates.io and its API reference is on docs.rs. For a step-by-step tutorial in Spanish, see Cómo crear rutas multiidioma en Laravel Rust on Neoguias.

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 of routes, the view functions and, when fallback is on, the localized fallback.

A route per language

Instead of route.get, use LocalizedRoute::get. The router is its first argument, because Laravel Rust has no global Route facade. The locales are written with locales!, and any locale can carry its own translated path.

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");
}

That generates /dashboard in English and /es/panel in Spanish. A bare "en" reuses the first parameter, and "es" => "panel" gives that locale its own path. The default locale gets no prefix, and every other locale is prefixed with its code unless you configure a different prefix. The routes are registered when the statement ends, so chain .name(), .middleware() and the rest in the same statement. The handler is shared by every language, so it must be Clone, which functions and closures that capture nothing are.

post, put, patch, delete, options, any and r#match (the list of methods as strings) work the same way. LocalizedRoute::prefix("admin").group(route, ..) replaces Route::prefix('admin')->group(), because the locale prefix has to go first.

Resources

LocalizedResource::make registers a resource once per locale. Laravel Rust has handler functions rather than controllers, so a resource is the set of handlers you give it, and create and edit can be translated per locale:

use laralang::{LocalizedResource, ResourceHandlers, locales};

LocalizedResource::make(
    route,
    "photos",
    locales!["en", "es" => ("fotos", "create" => "crear", "edit" => "editar")],
    ResourceHandlers::new().index(photos::index).create(photos::create).show(photos::show),
);

The route names use the base resource name in every locale, and the route parameter is in every language, so a single handler keeps working no matter which language resolved the URL. LocalizedResource::api() skips create and edit.

Linking to them

Laravel Rust 0.1 has no named routes, so Laralang keeps the registry that names them. laralang::route() resolves a name to a URL in the current language, and a name that starts with one of your locales targets that language:

laralang::route("dashboard", ())?;                          // the current language
laralang::route("es.dashboard", ())?;                       // Spanish
laralang::route("es.services.show", [("slug", "hola")])?;   // /es/servicios/hola
laralang::route("services", [("page", 2)])?;                // /services?page=2
laralang::route_with("services", (), false)?;               // "/services", relative

A parameter the URI does not name becomes the query string. An unknown name, or a missing parameter, is a 500 error. In MiniJinja views route() is a function with the same name, and it also knows the names of Laravel Rust's own route(), so existing templates keep working:

<a href="{{ route('dashboard') }}">Dashboard</a>
<a href="{{ route('services.show', slug='hola') }}">Hola</a>

Alternates and hreflang

laralang::alternates() returns the current route in every configured locale, ready for language switchers, hreflang tags and multi-locale sitemaps. alternates_with(params, absolute) overrides the parameters or asks for relative paths.

let alternates = laralang::alternates()?;
// en -> https://example.com/services
// es -> https://example.com/es/servicios

async fn show() -> laravel::Result<View> {
    laralang::merge_alternates()?;

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

merge_alternates() puts the hreflang links in the page's head, so a layout that prints {{ head() }} has them. In a template, laralang_alternates() gives the pairs for a switcher, and route_is('services') matches that route in any language, so active states in a menu keep working. If a route exists in a subset of locales, only those are returned, so there are no dead links.

Detecting the locale

Every localized route carries its own SetRouteLocale, so the language of the URL needs nothing from you. For the rest, Laralang comes with the middleware of the PHP package, which sets the locale with laralocale::with_locale:

  • SetRouteLocale reads the first segment of the URL.
  • SetSessionLocale applies the locale stored in the session, for internal routes such as an admin panel.
  • SetBrowserLocale reads Accept-Language when the session has none, for public routes.
  • SetSmartLocale does the universal one: the URL prefix first, then the session or the browser.

They are idempotent, and they are separate on purpose, so public routes and an admin panel can each detect the language the way that fits them.

The localized fallback

A URL is often shared with the wrong prefix, or none. With fallback on, a URL that matches no route but exists under another locale is redirected there with a 301: /servicios goes to /es/servicios, and /es/services to /services. Parameters and the query string travel along, and anything that cannot be rescued keeps its 404. Locales are tried with the default one first, so the destination depends only on the path and never on the visitor, which is what makes a permanent redirect safe.

A later fallback replaces an earlier one, including the one Laravel Rust's starter app registers. If your application has its own, leave fallback off and call laralang::localized_fallback(request).await from yours.

Configuration

LaralangConfig is the configuration section, set in src/app.rs with with_config. It is the counterpart of config/locales.php of the PHP package:

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

The default language never carries a prefix. It is the locale of Laralocale, not the first entry of supported. Give it a prefix of its own and every language gets one and nothing lives at the root, so turn fallback on, which sends the visitor from / to their own language with a 302. Decide the shape of your URLs before going live: the permanent redirects are cached by browsers and CDNs, and changing prefixes afterwards leaves old clients following redirects to addresses that no longer exist.

Ziggy

Laravel Rust has no Ziggy, so laralang::ziggy() returns the route registry in the shape of Ziggy 2's payload. Share it through Inertia and Ziggy's JavaScript route() reads it:

Ok(props! { ziggy => laralang::ziggy() })

Differences from the PHP package

  • The router is an argument. LocalizedRoute::get(route, "uri", locales, handler), where PHP has LocalizedRoute::get('uri', locales, action). match is written r#match.
  • Locales are locales!["en", "es" => "panel"], a macro that reads like PHP's array.
  • Handlers, not controllers. A resource takes a ResourceHandlers set. names(), shallow() and scoped() are not ported.
  • Registration happens when the statement ends. Chain .name() and the rest in the same statement.
  • The registry is the package's. route(), alternates() and route_is() read the routes Laralang registered, and only those. On a route registered with route.get() alternates() is empty.
  • Router::prefix cannot put the locale first, so LocalizedRoute::prefix("admin").group(route, ..) replaces it for localized routes.
  • alternates() is two functions, alternates() and alternates_with(params, absolute).
  • URL parameters are values you pass, [("slug", "hola")]. A model is not filled with its key.
  • The fallback answers 404, not 405, to a POST, and only rescues the routes Laralang registered.
  • No signed localized URLs and no Blade @routes. Laravel Rust signs URLs by handler, and its views are MiniJinja.

built and maintained by Edu Lazaro · MIT license