
# Laratext for Laravel Rust
<p align="center">
<a href="https://github.com/edulazaro/laratext-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laratext-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laratext"><img src="https://img.shields.io/crates/v/laratext" alt="Crates.io"></a>
<a href="https://crates.io/crates/laratext"><img src="https://img.shields.io/crates/d/laratext" alt="Downloads"></a>
<a href="https://docs.rs/laratext"><img src="https://img.shields.io/docsrs/laratext" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laratext-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laratext" alt="License"></a>
</p>
## Introduction
Laratext manages and auto-translates the text strings of your application. When you translate with a gettext style helper you give it either the key or the text, and both have issues. If you give the key, the language file becomes difficult to read, as you do not know what is in it. If you give the text, your translations break when you change a single character. With Laratext you give both, the key and the text, which makes it useful and readable.
It also connects translation services (OpenAI, Claude, Google Translate or Translatorio) to translate the missing keys into as many languages as you need.
```rust
text("key_name", "default_value");
text!("hello_mate"); // "Hello Mate"
```
```html
{{ text('key_name', 'default_value') }}
```
It is the port of [Laratext](https://github.com/edulazaro/laratext), 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.
It includes these features:
* Keys with their source text, so the language files stay readable.
* Auto-translation of the missing keys into several languages.
* Four translation services: OpenAI, Claude, Google Translate and [Translatorio](https://translatorio.com), plus any of your own.
* The `text()` function and the `text!` macro in Rust, and the `text()` function in MiniJinja views.
* Placeholders and plurals, with the rules of Laravel.
* `text()` in React, Vue, Svelte and Alpine, sharing the translations through Inertia or a script tag.
* Commands to scan your project, lock the translations a person has reviewed, and write translators.
## Requirements
- Laravel Rust `0.1`
- [`laralocale`](https://github.com/edulazaro/laralocale-rust), which holds the current locale with the API of the localization that Laravel Rust is preparing (`laralocale::locale()`, `set_locale()`, `request.preferred_locale()`). Laravel Rust 0.1 has no localization, so Laratext reads the locale of each request from it and never builds a second mechanism.
- Node.js, only to run the JavaScript tests of this crate.
## Installation
```bash
cargo add laratext laralocale
```
Register both service providers in `src/app.rs`, and list the locales you support:
```rust
use laralocale::{LaralocaleServiceProvider, LocaleConfig};
use laratext::{LaratextServiceProvider, TextsConfig};
use laravel::Application;
pub fn configure() -> ApplicationBuilder {
Application::configure()
.with_providers(|providers| {
providers.add(LaralocaleServiceProvider::new());
providers.add(LaratextServiceProvider::new());
})
.with_config(|config, _| {
config.section_mut::<LocaleConfig>().supported = ["en", "es", "fr"].map(str::to_owned).to_vec();
let texts = config.section_mut::<TextsConfig>();
texts.languages = [("en", "English"), ("es", "Spanish"), ("fr", "French")]
.into_iter()
.map(|(code, name)| (code.to_owned(), name.to_owned()))
.collect();
})
}
```
Laralocale does not choose the language of a request by itself: add a middleware that calls `laralocale::set_locale(request.preferred_locale())`, as its README shows, or use `LaralocaleServiceProvider::new().with_detection()` to detect it from the query string, the session, a cookie or the browser.
The provider adds the configuration, the commands, the translators, the `text()` and `texts()` functions in the views and the JavaScript module under `/vendor/laratext/`.
The translations live in `lang/{locale}.json`, in the base path of the application, as in Laravel. Laravel Rust has no `lang_path()`, so `TextsConfig::lang_path` (`lang` by default) names the folder.
## Configuration
`TextsConfig` is the configuration section, the equivalent of `config/texts.php`. It has the same keys and the same defaults as the PHP file, in snake case. The API keys and the models read the same environment variables, and everything else is set in `src/app.rs` with `with_config`:
```rust
Application::configure().with_config(|config, _| {
let texts = config.section_mut::<TextsConfig>();
texts.default_translator = "claude".to_owned();
texts.context = "A real estate CRM used by estate agents. Address the user formally.".to_owned();
texts.openai.timeout = 120;
})
```
| Key | Default | |
| --- | --- | --- |
| `default_translator` | `openai` | The translator `laratext:scan` uses without `--translator` |
| `openai.api_key` | `OPENAI_API_KEY` | |
| `openai.model` | `gpt-5.4-nano`, or `OPENAI_MODEL` | |
| `openai.timeout`, `openai.retries` | `60`, `3` | Seconds, and attempts per request |
| `openai.max_output_tokens` | `4096` | The longest answer asked for. The model's own limit caps it |
| `openai.reasoning_effort` | `None` | Overrides the effort sent to a reasoning model |
| `claude.api_key` | `ANTHROPIC_API_KEY` | |
| `claude.model` | `claude-haiku-4-5`, or `ANTHROPIC_MODEL` | |
| `claude.timeout`, `claude.retries` | `60`, `3` | |
| `claude.max_tokens` | `4096` | The longest answer asked for. The model's own limit caps it |
| `google.api_key` | `GOOGLE_TRANSLATOR_API_KEY` | |
| `google.timeout`, `google.retries` | `20`, `3` | |
| `translatorio.api_key` | `TRANSLATORIO_API_KEY` | |
| `translatorio.url` | `https://translatorio.com`, or `TRANSLATORIO_URL` | Only changes for a self-hosted or local instance |
| `translatorio.glossary`, `.formality`, `.effort` | `TRANSLATORIO_GLOSSARY`, `TRANSLATORIO_FORMALITY`, `TRANSLATORIO_EFFORT` | |
| `translatorio.format` | `auto` | `auto`, `text`, `html` or `markdown` |
| `translatorio.timeout`, `translatorio.retries` | `180`, `3` | |
| `models` | empty | Corrections to what the package knows about a model |
| `languages` | `en`, `es`, `fr` | The languages the texts are translated into |
| `source_locale` | `None` | The language the texts in the code are written in |
| `context` | empty | What the translator is told about your application |
| `scan.scripts.paths` | empty | The folders with your scripts, such as `resources/js` |
| `scan.scripts.extensions` | `js`, `jsx`, `ts`, `tsx`, `vue`, `svelte` | |
| `scan.scripts.functions` | `text`, `$text` | |
| `lang_path` | `lang` | The folder with the language files. Not in the PHP package |
This is an example of the `.env`:
```
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
GOOGLE_TRANSLATOR_API_KEY=your_google_api_key
TRANSLATORIO_API_KEY=your_translatorio_api_key
```
### The language your source texts are written in
The scanner compares the text in your code with the one stored in the language file of your source language, and tells the translator to translate from it. By default that is the default locale of laralocale (`LocaleConfig::locale`, read from `APP_LOCALE`), which is right in most projects.
It is not right when they differ, and the usual case is an application that runs in one language while its source texts are written in English:
```rust
// APP_LOCALE=es
{{ text('portfolio.heading', 'Portfolio') }}
```
Here the Spanish translation, "Portafolio", would be compared against "Portfolio" and every key would look like its source text had changed, so a single `--write` would retranslate the whole project. Point the package at the right file:
```rust
texts.source_locale = Some("en".to_owned());
```
Leave it out and nothing changes: the application locale keeps being used.
### Giving the translator context
A translator sees short strings on their own, so it has to guess. "Book" can be a noun or a verb, and it has no way of knowing whether your application addresses people formally or that your product name must be left alone.
Fill in `context` and it is sent with every batch:
```rust
texts.context = "A real estate CRM used by estate agents. Address the user formally. Never translate the product names Inmoqueen or Laratext.".to_owned();
```
Use it for what the application does, the register you want, and the terms that must not be translated. It is optional: leave it empty and nothing is added to the prompt. Translators that take no prompt, such as Google Translate, ignore it.
Translation keys are used as context too. Since they travel to the translator with their text, a key like `nav.home` says that "Home" is a navigation link and should be "Inicio" rather than "Hogar". The prompt states that keys **may** be used this way, not that they must: a key like `common.name` says nothing useful, and one inherited from an older part of the codebase can be misleading, so the text itself always comes first.
### The translators included
Four translators ship with the package. Pick one for a scan with `--translator=`, or make it the project default with `default_translator`.
| Translator | `--translator=` | Key in `.env` | What it is |
|---|---|---|---|
| OpenAI | `openai` | `OPENAI_API_KEY` | OpenAI's chat models, `gpt-5.4-nano` unless `OPENAI_MODEL` says otherwise. Reads `context`. |
| Claude | `claude` | `ANTHROPIC_API_KEY` | Anthropic's [Messages API](https://docs.anthropic.com/en/api/messages), `claude-haiku-4-5` unless `ANTHROPIC_MODEL` says otherwise. Reads `context`. |
| Google Translate | `google` | `GOOGLE_TRANSLATOR_API_KEY` | The Google Cloud Translation API. It takes no prompt, so it ignores `context`. |
| [Translatorio](https://translatorio.com) | `translatorio` | `TRANSLATORIO_API_KEY` | A translation API that protects placeholders and tags itself and reports any that did not survive. Reads `context`. See below. |
```bash
laravel laratext:scan --write --translator=claude
```
The Claude translator runs with prompt caching enabled on the system prompt, so repeated batches in a single scan reuse the cached instructions automatically. For a service that is not on the list, [write your own translator](#creating-translators).
### What each model can do
Translating with `gpt-3.5-turbo` is not translating with `gpt-5.4-nano`: one answers 4,096 tokens at most and the other 128,000, one takes `temperature` and another refuses any request that sends it, one can be held to a JSON schema and another only asked for JSON. The OpenAI and Claude translators know the models of both providers (the same table as the PHP package) and act on it:
- **Batches are sized by the answer they produce, not by the text they send.** A batch into twenty languages answers twenty times its size, so it is cut to fit one answer: `max_output_tokens` for OpenAI and `max_tokens` for Claude (4,096 by default), capped by the model's own limit. When one string into every language would not fit, the languages go in groups. No batch is ever larger than the 2,000 characters and 100 keys of before.
- **An answer cut short at the limit is split, never sent again whole.** The batch is halved until it fits, so a long scan into many languages never pays three times for the same truncated answer.
- **Each model gets only the parameters it accepts.** `temperature: 0` goes to the models that take it. Reasoning models get `reasoning_effort`: `none` where the model can skip reasoning, otherwise the least it takes, and room on top of the answer for the reasoning they do. Models that support Structured Outputs answer against a JSON schema with exactly the keys and languages asked for; older ones in JSON mode.
- **The source language is never sent**: its file gets the source text.
- **Regional codes are kept**: `pt_BR` and `zh_CN` are written under the code you use, whether the model answers `pt-BR` or `zh`.
A model the package does not know is asked the way every model was before: a 4,096-token answer and no parameter it might refuse. Correct a model or add a new one with `models`, by its name or a prefix of it:
```rust
use laratext::ModelOverride;
texts.models.insert(
"gpt-6".to_owned(),
ModelOverride::new()
.max_output_tokens(128_000)
.temperature(false)
.json("schema")
.reasoning(true)
.reasoning_effort("low"),
);
```
`json` is `schema`, `object` or `none`. A field you leave out keeps what the package knows. A reasoning model takes longer per request: give it a `timeout` of 180 seconds or more.
### Translatorio
[Translatorio](https://translatorio.com) is a translation API built for this kind of job: it takes placeholders (`:name`, `{count}`, `%s`), HTML tags and links out of the text before the model sees it and puts them back afterwards, so a translated string can never lose its `:count`. It also reports when a placeholder did not survive, and the scan prints a warning for that key instead of writing a broken string silently.
```bash
laravel laratext:scan --write --translator=translatorio
```
The options specific to it:
- `glossary`: the slug of a glossary on your Translatorio account, the terms your product always translates the same way.
- `formality`: `default`, `formal` or `informal`.
- `effort`: which model translates, `default`, `low`, `medium` or `high`.
- `format`: `auto` sends the strings with HTML tags as `html`, so their tags are protected too, and the rest as `text`. Set `text`, `html` or `markdown` to send every string that way.
The `context` above is sent with every batch, up to 30,000 characters. Laravel locale codes such as `pt_BR` or `zh_CN` are written back under the same code, the source language is never sent (its file gets the source text), and more than twenty languages go in several calls.
Retries on `429`, `5xx`, a call still running after a timeout and a connection failure reuse the same `Idempotency-Key`, so a retried batch is never charged twice, and they wait as long as the API asks. A `402` (out of credits) is never retried: on the first batch it stops the scan with the API's own message; later on, the scan keeps and writes what was already translated and sends nothing more, and the next scan finishes the rest. Any other batch that fails after a good one is skipped and reported, like the other translators do.
## Usage
Here is how you use the `text` function, the `text!` macro and the MiniJinja function.
Use the `text()` function to fetch translations within your Rust code:
```rust
text("key_name", "default_value");
```
Use the `text()` function in your views, which are MiniJinja templates:
```html
{{ text('key_name', 'default_value') }}
```
The `text!` macro takes the arguments of the PHP helper, `text($key, $default, $replace, $locale)`, because a Rust function has no optional arguments:
```rust
text!("key_name");
text!("key_name", "default_value");
text!("key_name", "default_value", replace! { name => "John" });
text!("key_name", "default_value", replace! { name => "John" }, "es");
```
They all call `Text::get(key, Some(default), &replace, locale)`, which is the PHP `Text::get()` with the same arguments.
The current locale is the one of laralocale: the request's, set by your middleware with `laralocale::set_locale()` or by its `DetectLocale`, or the one you set with `laralocale::with_locale()`. A key that is missing from the language file of that locale is looked up in the one of its language (`pt` for `pt_BR`) and then in the one of the fallback locale (`laralocale::fallback_locale()`), the chain of `laralocale::candidates()`, before the source text is used.
A function in a template escapes what it prints, as everything in MiniJinja does. Use `| safe` for a translation that carries HTML you wrote yourself.
### Auto-Generated Text from Keys
You can also use just the key without providing a default value. The system will automatically generate readable text from the key name:
```rust
text!("hello_mate"); // Auto-generates: "Hello Mate"
text!("welcome_back"); // Auto-generates: "Welcome Back"
text!("user.first_name"); // Auto-generates: "First Name" (uses last part after dot)
```
```html
{{ text('hello_mate') }} {# Auto-generates: "Hello Mate" #}
{{ text('welcome_back') }} {# Auto-generates: "Welcome Back" #}
{{ text('pages.contact_us') }} {# Auto-generates: "Contact Us" #}
```
The auto-generation works by:
- Taking the last part after dots (e.g., `pages.contact_us` → `contact_us`)
- Replacing underscores with spaces (e.g., `contact_us` → `contact us`)
- Capitalizing each word (e.g., `contact us` → `Contact Us`)
The scanner writes the same text to the language files, so the application reads the same before and after the next scan.
### Replacement Texts (Placeholders)
You can include placeholders in your text strings using the `:placeholder` syntax. These placeholders will be preserved during translation and can be replaced with actual values when displaying the text.
**Basic usage without replacements:**
```rust
// Displays the text as it is, with its placeholders
text("welcome.user", "Welcome, :name!");
// Output: "Welcome, :name!"
```
**Usage with replacement values:**
```rust
use laratext::{replace, text};
text!("welcome.user", "Welcome, :name!", replace! { name => "John" });
// Output: "Welcome, John!" (or "¡Bienvenido, John!" in Spanish)
text!("items.count", "You have :count items.", replace! { count => 5 });
// Output: "You have 5 items." (or "Tienes 5 artículos." in Spanish)
```
```html
{{ text('welcome.user', 'Welcome, :name!', {'name': user.name}) }}
{{ text('file.uploaded', ':count file uploaded.', {'count': file_count}) }}
```
`replace!` builds a `Replace`, the equivalent of the `$replace` array. A name is an identifier or a string, and a value is text, a number, a boolean, `None`, or a closure that wraps a `<name>...</name>` tag:
```rust
use laratext::{Replace, ReplaceValue};
let replace = Replace::new().with(
"link",
ReplaceValue::callback(|inner| format!("<a href=\"/terms\">{inner}</a>")),
);
text!("accept", "Read the <link>terms</link>", replace);
```
`:name`, `:Name` and `:NAME` take the value as it is, with its first letter in capitals and all in capitals, and the longest placeholder goes first, so `:name_full` is never read as `:name`.
When these texts are scanned and translated, the placeholders (`:name`, `:count`, etc.) will be preserved in all target languages.
### Plurals
Separate the forms with `|` and pass the quantity as `count`, which is the same syntax Laravel uses:
```rust
text!("items.count", "One item|You have :count items", replace! { count => n });
```
```html
{{ text('items.count', 'One item|You have :count items', {'count': cart_items}) }}
```
```
count = 1 -> "One item"
count = 5 -> "You have 5 items"
```
The form is chosen by the rules of Laravel's `MessageSelector`, the same table of 280 locales, so the rules of each language apply. A language with three forms uses three, and the translated file drives the choice:
```json
// lang/ru.json
{ "items.count": "яблоко|яблока|яблок" }
```
Explicit ranges work as well, for when the wording changes at a threshold rather than at the singular:
```rust
text!("items.count", "{0} No items|[1,19] You have :count items|[20,*] You have plenty", replace! { count => n });
```
Both signals are needed for this to kick in, a `|` in the text and a numeric `count` in the replacements. A text that merely contains a pipe is returned untouched, so `text("shortcut", "Ctrl|Alt")` keeps being `Ctrl|Alt`.
Note that the translator decides how many forms each language gets. Review the result for languages with more forms than your source language, and lock the key once it is right:
```bash
laravel laratext:lock items.count --lang=ru
```
## JavaScript: React, Vue, Svelte and Alpine
The same call works in the browser, with the same key, source text, placeholders and plurals:
```js
text('cart.total', 'Total: :amount', { amount: '12 €' })
text('cart.items', 'One item|:count items', { count: 3 })
```
It takes three pieces, all in this crate: the scanner finds the calls in your scripts, Laravel Rust hands each page only the translations it needs, and a small JavaScript module (no npm install) looks them up the way `text()` does in Rust.
### Setup
List the folders with your scripts in the configuration, so `laratext:scan` reads them too:
```rust
texts.scan.scripts.paths = vec!["resources/js".to_owned()];
```
The module is in `resources/js` of the crate, and the application serves it as it is under `/vendor/laratext/`, so a page without a bundler can import it:
```html
<script type="module">
import { text } from "{{ vendor_asset('laratext', 'index.js') }}";
</script>
```
A bundler needs the files in your project. Copy them with the `laratext:publish` command, which writes `resources/js/vendor/laratext` (use `--to` for another folder and `--force` to overwrite):
```bash
laravel laratext:publish
```
Point an alias at the module in `vite.config.js`:
```js
import path from 'node:path';
export default defineConfig({
resolve: {
alias: {
'@laratext': path.resolve(__dirname, 'resources/js/vendor/laratext'),
},
},
});
```
TypeScript declarations are included.
### Pages rendered by MiniJinja
For Alpine, or React, Vue and Svelte components mounted on a server rendered page, print the translations the page needs with `texts()`, by key prefix:
```html
<head>
{{ texts(['header', 'cart']) }}
</head>
```
It prints a `<script type="application/json">` with the keys `header`, `header.*`, `cart` and `cart.*` in the current language. The language file itself never reaches the browser. A layout and a view can each print their own, and they are merged.
```js
// React, Svelte or plain JavaScript
import { text } from '@laratext';
text('header.search', 'Search');
```
```js
// Vue: $text in templates
import { laratext } from '@laratext/vue';
createApp(App).use(laratext).mount('#app');
```
```js
// Alpine: $text in any component, x-text="$text('cart.empty', 'Your cart is empty')"
import laratext from '@laratext/alpine';
Alpine.plugin(laratext);
```
After a Livewire (`wire:navigate`) or Turbo navigation, the new page's `texts()` is read again.
### Inertia
Share the translations as props with `Text::frontend()`, the common ones from the middleware and each page's own from its handler:
```rust
use laratext::Text;
use laravel::inertia::{self, Props, props};
// HandleInertiaRequests::share()
async fn share(&self, _request: &Request) -> laravel::Result<Props> {
Ok(props! {
texts => Text::frontend(["header", "footer"], None),
})
}
// A handler
pub async fn cart() -> inertia::Page {
inertia::render("Cart", props! {
pageTexts => Text::frontend("cart", None),
})
}
```
`Text::frontend()` returns a `Frontend`, `{ locale, lines }`, which serialises as what the module reads, so it is a prop as it is.
Tell the module which props hold them, once, in `app.js` (and `ssr.js`). The default is `['texts']`:
```js
import { configure } from '@laratext';
configure({ props: ['texts', 'pageTexts'] });
```
```jsx
// React
import { useText } from '@laratext/inertia/react';
const text = useText();
return <h1>{text('cart.title', 'Your cart')}</h1>;
```
```js
// Vue: $text in templates, useText() in <script setup>
import { laratext } from '@laratext/inertia/vue';
createSSRApp({ render: () => h(App, props) }).use(plugin).use(laratext);
```
```svelte
<!-- Svelte, with Inertia 2 or 3 -->
<script>
import { useText } from '@laratext/inertia/svelte';
const text = useText();
</script>
<h1>{text('cart.title', 'Your cart')}</h1>
```
With Inertia the function comes from `useText()` rather than an import: server-side rendering renders several requests in the same Node process, and `useText()` reads the translations of the page being rendered, never a dictionary shared between requests.
### How the calls must be written
- The key and the text are literal strings, in single, double or back quotes. A call with a variable, a concatenation or a template literal with `${}` cannot be scanned: `laratext:scan` lists each one with its file and line instead of guessing.
- A call can span several lines, and the third argument can be anything.
- The scanner looks for `text` and `$text`. If your components call the function something else, add the name: `texts.scan.scripts.functions = vec!["text".into(), "$text".into(), "t".into()]`.
- A key not translated yet shows its source text, as in Rust. The plural and placeholder rules are Laravel's, and the tests compare the JavaScript against Rust in every language Laravel knows.
- Plurals follow the current Laravel 13, which reads a negative count by its absolute value and allows spaces inside `{ 0 }` and `[ 1,* ]`.
## Scanning Translations
You can use the `laratext:scan` command to scan your project files for missing translation keys and translate them into multiple languages:
```bash
laravel laratext:scan --write
```
The scanner reads your Rust files and your MiniJinja templates (`.html`) statically, and the scripts of `scan.scripts.paths`, so the key must be a literal string. `text(&key)` or `text(&format!("prefix.{name}"), ...)` will work at runtime if the key already exists, but the scanner will never see it, so it is never created or translated.
It reads these calls:
```rust
text("key", "Source");
text!("key", "Source", replace! { name => name });
text!("key");
Text::get("key", Some("Source"), &replace, None);
```
```html
{{ text('key', 'Source', {'name': name}) }}
{{ text('key') }}
```
A key built at run time is skipped, and it is worth avoiding for a second reason: the scanner cannot report it as missing, so a language that lacks it shows the source text to the user and nothing warns you. Write one literal call per case instead:
```rust
// The scanner sees nothing here
text(&format!("activity.{}", kind), &default)
// It sees every key here
match kind {
Kind::Created => text("activity.created", ":actor created :item"),
Kind::Deleted => text("activity.deleted", ":actor deleted :item"),
}
```
The scanner never enters `vendor`, `node_modules`, `storage`, `tests` or `target`, wherever they are, nor `bootstrap/cache` or a folder that starts with a dot.
You can also specify the target language or the translator to use:
```bash
laravel laratext:scan --write --lang=es --translator=openai
```
These are the command Options:
* `--write`: Write the missing keys to the language files.
* `--lang`: Target a specific language for translation (e.g., es for Spanish).
* `--dry` Report what a real run would do without writing anything and without calling the translator.
* `--diff`: Show the diff of the changes made.
* `--resync`: Retranslate **every** key from scratch, ignoring existing translations (use after changing translator or model).
* `--only-missing`: Only translate brand-new keys; skip keys whose source text has drifted (they are listed as warnings instead).
* `--prune`: Remove keys present in lang files but no longer referenced in code.
* `--translator`: Specify the translator service to use (e.g., openai or google).
#### Looking before spending: `--dry`
`--dry` compares your code with the language files and reports what a real run would do. It writes nothing and, more importantly, never calls the translator, so it costs nothing:
```bash
laravel laratext:scan --dry
```
```
Found 5579 unique keys.
Dry run, nothing was written and the translator was not called.
0 new key(s)
0 key(s) with a changed source text, 0 of them would be retranslated
313 orphan key(s) in the language files
Nothing would be sent to the translator.
```
It combines with the other flags, so `--dry --only-missing` shows how many drifted keys would be left alone, and `--lang=es` narrows the comparison to one language.
Note that dropping `--write` is not the same thing. Without `--dry` the command translates and simply does not save the result, so it spends tokens all the same. `--dry` is the one that costs nothing.
### Keeping Translations In Sync
By default, `laratext:scan --write` translates:
1. **New keys**: keys in code that don't exist yet in the lang files.
2. **Drifted keys**: keys whose source text in code no longer matches the value stored in the language file of the source language. These are retranslated in every target language so translations stay aligned with the source.
```bash
laravel laratext:scan --write
# ℹ️ 1 key(s) will be retranslated because their source text changed:
# • pages.home.welcome
# old: "Welcome"
# new: "Welcome to our site"
# ... (translator called, JSONs updated)
```
#### Skipping drift: `--only-missing`
If you want the conservative behaviour (translate only new keys, leave drifted keys untouched), pass `--only-missing`. Drift is still detected and printed as a warning, but no API calls are made for drifted keys:
```bash
laravel laratext:scan --write --only-missing
# ⚠️ 1 key(s) have an updated source text but stale translations in es, fr:
# • pages.home.welcome
# old: "Welcome"
# new: "Welcome to our site"
# Drop --only-missing to retranslate them, or edit the JSON files manually.
```
#### Protecting reviewed translations: locking keys
`--only-missing` is all or nothing: it stops every drifted key from being retranslated. When a translator reviews a single string and you want that one string protected forever, lock it:
```bash
laravel laratext:lock save # in every configured language
laravel laratext:lock save --lang=es # only in Spanish
laravel laratext:lock "errors.*" # wildcards are allowed
laravel laratext:lock --all --lang=es # every key currently in es.json
```
A locked key is never written by the scanner. It is not retranslated when the source text drifts, it is not touched by `--resync`, and it is not removed by `--prune`. Locks are per language, so protecting a Spanish correction still lets French follow the English source.
Unlocking is symmetric, and `--all` asks for confirmation because the damage only shows up on the next scan:
```bash
laravel laratext:unlock save --lang=es
laravel laratext:unlock --all --lang=es
laravel laratext:unlock --all --force # no question, for scripts
```
Locks live in `lang/.locked/{locale}.json` as a plain list of keys, so they are easy to review in a diff. Commit them: they are a decision about your translations, not local state. If nothing is locked the files do not exist and the scanner behaves as if locks did not exist.
When a scan skips something, it says so:
```
🔒 es: 1 key(s) kept as they are, they are locked.
🔒 1 key(s) not sent to the translator, they are locked in every language.
```
That second line is also a saving: a key locked everywhere never reaches the API.
#### Forcing a full retranslation: `--resync`
`--resync` retranslates **every** key in your codebase from scratch, even keys whose source text has not changed. Useful when you've switched translator providers, upgraded the OpenAI model, or want to regenerate inconsistent translations left over from older runs. Expect this to be expensive in tokens.
```bash
laravel laratext:scan --write --resync
```
#### Cleaning up orphan keys: `--prune`
`--prune` detects the opposite drift: keys that still live in `lang/{locale}.json` but are no longer referenced anywhere in code (removed `text()` calls). By default it only lists them; combined with `--write` it removes them from every configured language file:
```bash
laravel laratext:scan --prune # list orphan keys only
laravel laratext:scan --write --prune # actually delete orphan keys
```
#### Recommended cadence
* **During development**: run `laravel laratext:scan --write` after adding or editing `text()` calls. New keys get translated; edited source texts get retranslated automatically.
* **Periodically (weekly / pre-release / CI)**: run `laravel laratext:scan --write --prune` to also drop orphan keys left behind by refactors.
* **After switching model or translator**: run `laravel laratext:scan --write --resync` once to regenerate every translation against the new backend.
The language files are written as the PHP package writes them: JSON with four spaces of indentation, unicode and slashes unescaped, no newline at the end, and the keys in the order they were added.
## Creating translators
To create a custom translator, implement the `Translator` trait. Only `translate` is required, which is PHP's `TranslatorInterface`.
To facilitate the creation of custom translators, the `make:translator` command generates the file for a new one:
```bash
laravel make:translator BeautifulTranslator
```
This creates `src/translators/beautiful_translator.rs`:
```rust
use async_trait::async_trait;
use laratext::{TranslateError, Translated, Translator};
pub struct BeautifulTranslator;
#[async_trait]
impl Translator for BeautifulTranslator {
async fn translate(&self, text: &str, _from: &str, to: &[String]) -> Result<Translated, TranslateError> {
// The scan passes every configured language in `to`, the source language `from` included, unless
// this translator returns a number from `output_token_limit`. The bundled translators answer `from`
// with `text` and never ask a service for it. Do the same, or the service is asked to translate a
// language into itself, or a dictionary has no entry for it.
// TODO: Implement your translation logic here.
let mut results = Translated::new();
for language in to {
results.insert(language.clone(), text.to_owned()); // Dummy return same text
}
Ok(results)
}
}
```
Declare the module and register the translator under a name in `src/app.rs`, which is what `texts.translators` does in PHP:
```rust
providers.add(LaratextServiceProvider::new().translator("beautiful", || BeautifulTranslator));
```
Then `--translator=beautiful` picks it, and so does `default_translator`. A name that is registered again replaces the one before it, so you can swap a bundled translator for your own.
The `translate` method, which translates a single string into one or more target languages, is required:
```rust
async fn translate(&self, text: &str, from: &str, to: &[String]) -> Result<Translated, TranslateError>
```
**`to` can contain the source language.** `laratext:scan` passes every language of `languages` as a target,
the source language `from` among them, and `translate` and `translate_many` receive it as they get it. Only a
translator that returns a number from `output_token_limit` is spared: `batch_translate` answers the source
language with the source text itself and sends the others. The bundled translators handle `from` on their own,
so a custom one has to as well: answer it with the text as it is, instead of asking a service or a dictionary
for a translation into the language the text is already in.
```rust
for language in to {
if language == from {
results.insert(language.clone(), text.to_owned());
continue;
}
// Ask the service for `language`.
}
```
PHP does the same: its `Translator::batchTranslate` only takes the source language out when `outputTokenLimit()`
returns a number, and its `make:translator` stub does not mention it. Compare codes with `laratext::translator::same_language`
when `from` and `to` may spell a locale differently, such as `pt_BR` and `pt-br`.
Optionally, you can override `translate_many` to translate multiple texts in a batch, which can improve performance when supported by the translation API:
```rust
async fn translate_many(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError>
```
If `translate_many` is not overridden, each text is translated with `translate`. For full support both methods are recommended, so there are fewer requests and the result is cost effective.
`batch_translate`, which the scan calls, cuts the texts into requests of at most 2,000 characters and 100 keys. Override `max_payload_chars` and `max_batch_items` to change them. A translator that returns a number from `output_token_limit` has its batches sized by the answer they produce, and one that returns `TranslateError::Truncated` from `translate_batch` has the batch split, as the OpenAI and Claude translators do. Say what the translator is doing with `laratext::log_to_console`, and read the application's `context` with `context_instruction()`.
## Testing
The translators go through the HTTP client of Laravel Rust, so `client::fake()` intercepts every request and nothing leaves your machine:
```rust
use laravel::http::client;
let http = client::fake().with(
"api.openai.com/*",
json!({ "choices": [{ "message": { "content": json!({ "save": { "es": "Guardar" } }).to_string() } }] }),
);
app.command("laratext:scan --write --translator=openai").await.assert_successful();
http.assert_sent_count(1);
```
The language files are in the base path of the application, so give each test its own with `APP_BASE_PATH`, as this crate's tests do. Use `laralocale::with_locale("es", async { .. })` to run code in a locale.
## Differences from the PHP package
- **`text()` is a function of two arguments and a macro.** A Rust function has no optional arguments, so `text("key", "default")` is the function and `text!("key")`, `text!("key", "default", replace)` and `text!("key", "default", replace, "es")` are the macro, with the arguments of the PHP helper. `Text::get(key, Option<&str>, &Replace, Option<&str>)` is the PHP `Text::get()`.
- **A key alone makes its text at run time.** `text('hello_mate')` in PHP returns an empty string until the scanner has written the key, and `Text::get('hello_mate')` returns the key. Here both return `Hello Mate`, the text the scanner writes, so the application reads the same before and after a scan.
- **`replace!` and `Replace` take the place of the `$replace` array.** Closures work the same way, through `ReplaceValue::callback`. From a template, the replacements are a map, `{'name': name}`, and a closure cannot be passed.
- **No Blade directives.** `@text` is the MiniJinja function `text()`, with the same arguments by position or by name (`key`, `default`, `replace`, `locale`), and `@texts` is `texts()`. Like every MiniJinja expression they escape what they print, where `@text` echoes the text as it is.
- **The locale comes from laralocale.** Laravel Rust has no localization, so `App::getLocale()` and `App::getFallbackLocale()` are `laralocale::locale()` and `fallback_locale()`. A key missing from the language file of the locale is looked up in the one of its language and then in the one of the fallback locale before the source text is used. Laravel's translator does not fall back for JSON translations, so this is an addition.
- **Only JSON translations.** Laravel Rust has no PHP language files, so `lang/{locale}/{group}.php` is not read. The language files are the `lang/{locale}.json` of the PHP package, in the same format and the same place (the folder is `lang_path`, and `lang` by default), and the locks are in `lang/.locked/{locale}.json`.
- **Configuration is a typed section.** `TextsConfig` has the keys and the defaults of `config/texts.php`, in snake case, with `OPENAI_API_KEY`, `OPENAI_MODEL`, `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`, `GOOGLE_TRANSLATOR_API_KEY` and the `TRANSLATORIO_*` variables read from the environment. `lang_path` is new. `texts.translators` is not a key: translators are registered in the provider, with `LaratextServiceProvider::translator()`, because a name maps to Rust code. `texts.default_translator` takes a name, as the PHP file does (its README shows a class, its file a name).
- **`ModelLimits::for_model()`** replaces `ModelLimits::for()`, which is a keyword in Rust.
- **The scanner reads Rust and MiniJinja**, not PHP and Blade. It finds `text(`, `text!(` and `Text::get(` in `.rs` files and `text(` in `.html` templates, with the quotes of each language, raw strings in Rust and Rust's escapes. A call with a key alone is read when it ends with `)`, where PHP asked for `);`. The text of a call must be followed by `,` or `)`, which rules out a concatenation. The PHP rule about a double quoted key with a `$` is gone, because nothing interpolates in either language. `target` is excluded along with the folders PHP excludes. The script scanner is the PHP one.
- **The translators are traits and the HTTP client is Laravel Rust's.** The bundled ones keep the request, the headers, the batching, the truncation handling and the retries of the PHP ones. `ResponseTruncated` is `TranslateError::Truncated`, a `RuntimeException` is `TranslateError::Failed { message, code }`, and the waits between attempts go through a `Sleeper`, so a test can record them. `translateMany` of the OpenAI and Claude translators and `translateBatch` of all of them are as in PHP.
- **Messages while translating** (`➡️ Sending...`) are printed by `laratext:scan` as they arrive, through a channel the command opens around the translator. Outside the command a translator is silent.
- **A language file that is not valid JSON stops the scan** with an error and is never overwritten. PHP read it as empty and wrote over it.
- **`make:translator` creates `src/translators/{snake_case}.rs`** and prints the lines to declare and register it. It fails with exit status 1 on an error, where PHP's command returns 0.
- **The JavaScript module is served and published.** PHP points a Vite alias at `vendor/`. Here the crate serves the module under `/vendor/laratext/`, and `laratext:publish` copies it into the application for a bundler. The module is the same, and so are the tests: Node runs its unit tests and compares it with Rust in every locale.
- **`Text::frontend()` returns a `Frontend`** that serialises as `{ locale, lines }`, and `Text::script()` returns the `Html` of the tag. There is no Inertia glue to write: `Frontend` is a prop.
- **Plural rules of a locale spelled with a hyphen** (`pt-BR`) are read as `pt_BR`, which laralocale and Laravel Rust may produce.
## Sponsors
Laratext 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> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
Laratext for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).