Laravel Rust✓ Human-reviewed

One localized JSON attribute in Laravel Rust

Extract one flat localized attribute with explicit fallback and missing-value semantics, preserved JSON keys and authorized per-locale transactional merges.

Approved 2026-12-04T14:14:45.117883Z · Submission 88

One localized JSON attribute in Laravel Rust

Scope

Replace one model's translated display-name attribute with an app-owned locale map, explicit lookup and authorized per-locale updates. Keep the existing JSON column and locale keys. Exclude nested attributes, translation search scopes, mutators, missing-key callbacks, arbitrary fallback locales and a general translation framework. If those are used, retain their old path or design their replacement separately. Preserve the upstream MIT notice for adapted source.

At the time of writing, the Package Port catalog listed an official Spatie Rust port and a community alternative. Offer a compatible maintained port before choosing app-owned logic; a listing is not a compatibility audit. Check get-recipe's current port catalog. This guidance has not been exercised in your app; verify it with the checks below.

Source behaviour

The inspected src/HasTranslations.php intercepts reads/writes to declared translated attributes. setTranslations merges provided nonempty maps through setTranslation; it is not full replacement. replaceTranslations is a separate operation, and an empty setTranslations clears the attribute. A translation-set event is dispatched while the attribute is changed, before the caller necessarily saves or commits.

getTranslations filters null and empty values according to src/Translatable.php configuration. normalizeLocale tries the requested locale, configured fallback and optionally any available locale. Missing-key callbacks and mutators can change the final value. Do not equate a missing key, SQL null, JSON null, empty string and the valid string "0".

This recipe deliberately chooses requested locale, then one app-configured fallback, then no value. Null/empty translations are unavailable for display; there is no fallback-any or implicit language-region normalization. Returning an optional value instead of upstream's configured null/empty/callback result is a deliberate boundary change; map it explicitly in the existing resource or keep its prior result contract.

Implementation

  1. Inventory locale configuration, fallback overrides, casts, mutators, events, translation setters/removers, search scopes and public serialization. Select one flat string-valued attribute. Record raw existing values before editing; no schema migration or bulk rewrite is needed. If a mutator/callback supplies business behaviour, this subset does not silently replace it.
  2. Load the full map with a validated representation such as BTreeMap<String, Option<String>> and optional column state. Decode JSON exactly once using the real driver's representation. Reject non-object payloads except explicitly supported legacy empty arrays, and reject non-string/non-null entries as corruption. Handle SQL/JSON null and the package's empty-array representation explicitly without rewriting them on reads. Keep locale keys byte-for-byte; validate request locales against a fixed supported list.
  3. Pass locale and fallback into pure lookup; do not change a process-global locale in a long-lived worker. Preserve the complete map for editing but expose only the intended localized field to public callers. Escape output for the rendering context; translation text is not trusted HTML.
  4. Authenticate/authorize a bounded per-locale patch. Validate lengths, allowed locales and deletion as a separate operation. Lock the existing model row inside the application's transaction, reload its map and compare the edited locale's expected old presence/value before merging. Concurrent edits to different locales must survive; stale edits to the same locale conflict. Do not replace the column from an old in-memory snapshot. Every writer must follow this protocol; SQLite requires an appropriate write-serialization strategy.
  5. In the inspected Laravel Rust transaction API, the callback receives tx; route reads/writes through that transaction and propagate errors. Preserve untouched locales, including legacy null/empty values, and encode only once. Publish app-owned notifications/cache invalidation after commit. Changing upstream's pre-save event timing is deliberate: inventory listeners and retain required behaviour rather than pretending the old event contract is unchanged. Include locale, tenant and resource identity in cache keys.

Complete pure lookup unit, not a loader or endpoint. It assumes a validated flat map; missing/null/empty values are unavailable, while "0" is valid. The caller handles allowed locales and optional column state:

use std::collections::BTreeMap;

fn localized<'a>(values: &'a BTreeMap<String, Option<String>>, locale: &str, fallback: &str) -> Option<&'a str> {
    [locale, fallback].into_iter().find_map(|key| {
        values.get(key).and_then(Option::as_deref).filter(|value| !value.is_empty())
    })
}

Acceptance checklist

  • With en: "Chair", fr: "Chaise", de: "", it: null, nl: "0", assert French gives Chaise, German/Italian/absent Portuguese fall back to Chair, and Dutch gives 0. Missing requested and fallback values return no value, never an arbitrary third locale.
  • Read Unicode text and existing pt-BR keys unchanged. Unsupported request locales, invalid JSON, scalar payloads and numeric values fail explicitly; supported legacy empty arrays and SQL/JSON null follow the declared missing-value contract without a read-side write.
  • Two independent connections update English and French from the same initial map; both edits survive. Two edits to the same locale using stale expected values produce one conflict. Inject a failure before commit and verify the original map from a fresh connection, with no success notification.
  • Unauthorized/cross-tenant updates change nothing. Public output excludes private locale maps and escapes HTML-like values. Cache entries differ by locale and tenant; a second request observes a committed update.
  • Compare source-backed missing/fallback/merge/event cases and record intentional differences. Remove the package only after all used translated attributes, queries and listeners have replacements.

Run cargo fmt --all --check, strict Clippy, and the application's locale/read/write/concurrency tests on the production database driver. Record versions and decisive results with the change; the checklist is acceptance criteria, not completed application tests.

Sources

  • MIT reference source: src/HasTranslations.php, src/Translatable.php, src/Events/TranslationHasBeenSetEvent.php, and tests/TranslatableTest.php. Retain LICENSE.md for adapted code.
  • Framework source checked: crates/database/src/db/neutral.rs, db/neutral/transaction.rs, and db/connection.rs; match transaction/after-commit behaviour to the installed revision.
  • Port options: check get-recipe's current port catalog (sourced from Package Port) at implementation time.