Laravel PHP · Inline✓ Human-reviewed

App-owned localized JSON attributes in Laravel PHP

Inline one localized attribute with explicit missing/null/empty handling, safe JSON decoding, preserved locale keys and concurrency-safe per-locale patches.

Approved 2026-12-04T14:14:44.826299Z · Submission 87

App-owned localized JSON attributes in Laravel PHP

Scope

Inline one model's translated display-name attribute with a validated locale map, explicit lookup and authorized per-locale updates. Reuse its JSON column without bulk conversion. Exclude nested keys, mutators, missing-key callbacks, translation search scopes and a generic localization layer. Keep excluded callers on the package-backed path. Preserve the upstream MIT notice when adapting code, and check get-recipe's current port catalog when considering alternatives. This guidance has not been exercised in your app; verify it with the checks below.

Source behaviour

The inspected src/HasTranslations.php hooks translated attribute access. Its nonempty setTranslations merges supplied locale entries, whereas replaceTranslations replaces them; empty setTranslations clears the attribute. setTranslation changes the attribute and emits TranslationHasBeenSetEvent before a caller necessarily saves the model or commits.

getTranslations filters null/empty entries according to src/Translatable.php flags. normalizeLocale tries requested locale, configured fallback and optionally any available locale. Callbacks/mutators can change the returned value. Missing entries, null columns, null entries, empty strings and "0" need distinct handling; PHP's empty() would incorrectly reject "0".

This recipe deliberately uses requested locale, then one configured fallback, then null. Null/empty entries are unavailable for display; no fallback-any or implicit pt-BR to pt conversion occurs. If callers expect upstream's empty string, nullable or callback result, preserve that transport contract explicitly or document the deliberate difference.

Implementation

  1. Inventory the selected attribute's configuration, every reader/writer, setLocale, callbacks, mutators, translation scopes, events and public serialization. Do not remove the model's translation trait while other attributes still need it. Stage the selected caller behind an explicit method/service first and retire hooks only when every affected caller is migrated.
  2. Choose one JSON decoding boundary. Use the raw value with json_decode and JSON_THROW_ON_ERROR, or an explicitly throwing custom cast: the ordinary array cast can collapse corrupt JSON to null before validation. Decode as an object first if distinguishing an empty object from a legacy empty array matters. Validate a flat locale-to-string/null shape, explicitly supporting SQL/JSON null and the package's empty-array representation. No read operation should normalize stored data by writing it back.
  3. Pass an allowlisted locale and configured fallback into a pure lookup. Keep locale spelling unchanged and avoid changing process-global locale in long-lived workers. Return only authorized fields; escaping remains the renderer's job. A full locale map can expose unpublished content even if one locale is public.
  4. Authorize and validate a bounded per-locale patch; deletion must be explicit, not inferred from an omitted value. In the existing connection's DB::transaction, lock the current model row, reload the map and compare expected old presence/value for each edited locale. Merge into that current map, preserving untouched locales and null/empty values. Every writer must follow this protocol to prevent lost updates. Use a driver-compatible serialization strategy where row locks are unavailable.
  5. Save once using the chosen raw/cast representation. Eloquent save() can return false if an observer vetoes it; throw on that result so the transaction rolls back instead of reporting success. Publish app-owned notifications/cache invalidation after commit; that event timing deliberately differs from upstream's pre-save event and requires an inventory of listeners. Don't claim upstream events are preserved unless their payload, timing and listener contract really are. Use tenant/resource/locale-aware cache keys and reset per-request locale state in workers.

Complete pure lookup unit for a previously validated string/null array. It does not load JSON, validate the locale or authorize access; it preserves "0" and returns null when both choices are unavailable:

function localized(array $values, string $locale, string $fallback): ?string
{
    foreach ([$locale, $fallback] as $key) {
        $value = $values[$key] ?? null;
        if (is_string($value) && $value !== '') {
            return $value;
        }
    }
    return null;
}

Use an app-owned method/name appropriate to the selected attribute; don't add a global helper solely to copy this example.

Acceptance checklist

  • For en: "Chair", fr: "Chaise", de: "", it: null, nl: "0", assert French Chaise, German/Italian/absent Portuguese fallback Chair, Dutch 0, and null when both requested/fallback values are absent. Never choose an arbitrary third locale.
  • Preserve Unicode and pt-BR keys. Reject malformed/scalar JSON, numeric entries and unsupported request locales. SQL/JSON null and supported empty arrays follow the declared policy without read-side writes.
  • Two independent connections edit English/French from the same original map: both changes survive. Same-locale stale edits conflict. Inject failure before commit and assert the old JSON plus no success notification.
  • Deny unauthorized/cross-tenant updates and isolate caches by locale/tenant. A public resource must not expose the full edit map or render translation text as trusted HTML.
  • Compare package-backed merge, clearing, fallback and event semantics. Search all trait/scopes/static-helper usage and run composer why spatie/laravel-translatable before eventual removal.

Run the app's locale/resource/update feature tests and production-driver concurrency checks. Record PHP/Laravel/driver versions, outputs and deliberate compatibility differences with the change. These are acceptance criteria, not claims of completed app tests.

Sources

  • MIT reference source: src/HasTranslations.php, src/Translatable.php, src/Events/TranslationHasBeenSetEvent.php, and tests/TranslatableTest.php. Preserve LICENSE.md for adapted source.
  • Framework source checked: src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php and Database/Concerns/ManagesTransactions.php; match the application's casts and after-commit APIs.
  • Port options: check get-recipe's current port catalog (sourced from Package Port) at implementation time.