laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
![Laralang for Laravel Rust](art/banner.png)

# Laralang for Laravel Rust

<p align="center">
    <a href="https://github.com/edulazaro/laralang-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laralang-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
    <a href="https://crates.io/crates/laralang"><img src="https://img.shields.io/crates/v/laralang" alt="Crates.io"></a>
    <a href="https://crates.io/crates/laralang"><img src="https://img.shields.io/crates/d/laralang" alt="Downloads"></a>
    <a href="https://docs.rs/laralang"><img src="https://img.shields.io/docsrs/laralang" alt="Docs.rs"></a>
    <a href="https://github.com/edulazaro/laralang-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laralang" alt="License"></a>
</p>

## 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](https://github.com/edulazaro/laralang), the PHP package, to
[Laravel Rust](https://laravel.com/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](#differences-from-the-php-package) 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]https://github.com/edulazaro/laralocale-rust.
- 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]https://github.com/edulazaro/laralocale-rust, 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

```bash
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:

```rust
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:

```rust
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:

```rust
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:

```rust
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.

```rust
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.

```rust
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:

```rust
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

```rust
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:

```rust
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:

```rust
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:

```rust
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:

```rust
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:

```rust
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

```rust
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:

```rust
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`](https://docs.rs/laralang) value or positional values. A parameter the URI
does not name becomes the query string:

```rust
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:

```html
<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:

```rust
impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, _request: &Request) -> laravel::Result<Props> {
        Ok(props! { ziggy => laralang::ziggy() })
    }
}
```

```js
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:

```rust
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.

```rust
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:

```html
<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:

```html
<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:

```rust
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.

```rust
// 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:

```rust
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:

```rust
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:

```rust
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.

```rust
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:

<p>
  <a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a>&nbsp;<a href="https://kenodo.com">Kenodo</a>&nbsp;&nbsp;&nbsp;&nbsp;
  <a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a>&nbsp;<a href="https://andorradev.com">AndorraDev</a>
</p>

## Author

Created by [Edu Lazaro](https://edulazaro.com)

## License

Laralang for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).