One localized JSON attribute in Laravel Go
Scope
Bring one translated display-name attribute into the app as a flat locale map plus explicit read/update functions. Reuse existing JSON storage and locale keys. Exclude nested fields, arbitrary translation search, mutators, missing-key callbacks and a general localization framework. Preserve the MIT notice when adapting source. If the chosen attribute depends on excluded features, keep those callers on their original path until separately replaced.
At the time of writing, the Package Port catalog listed Spatie's official Go port. Offer it when compatible before implementing an app-owned subset, and check get-recipe's current port catalog. This guidance has not been exercised in your app; verify it with the checks below.
Source behaviour
In the inspected src/HasTranslations.php, locale-aware attribute access delegates to translation lookup. Nonempty setTranslations merges supplied entries; replaceTranslations replaces them and an empty setTranslations clears the map. setTranslation dispatches its event during attribute mutation, not after guaranteed persistence.
getTranslations filters null/empty values using src/Translatable.php settings. normalizeLocale chooses requested locale, configured fallback, and optionally any locale; missing callbacks and mutators can alter the result. SQL null, JSON null, no locale entry, empty string and "0" cannot be collapsed through Go zero values.
This recipe deliberately chooses requested locale, then one configured fallback, then an absent result. Empty/null values do not display, there is no fallback-any, and region keys are not automatically normalized. This differs from configurations returning empty strings, callback results or arbitrary available locales; adapt the transport contract deliberately.
Implementation
- Inventory the real attribute's writers, locale/fallback settings, mutators, events, search scopes and response shape. Keep the existing column. Select only a flat string-or-null map; retaining a parser/driver library is fine and does not require retaining a Laravel-specific wrapper.
- Decode exactly once into a validated map, such as
map[string]*string, plus explicit column state. Validate raw JSON shape before decoding: reject scalars/objects with non-string/non-null entries, distinguish SQL/JSON null, and explicitly support the package's legacy empty-array representation only as an empty map. Never treat every decode failure as an empty translation. Preserve all stored keys and untouched null/empty values on writes. - Validate requested locale against a fixed allowlist and pass locale/fallback explicitly. Do not put request-specific locale state in a global variable. Use the application's JSON response shape, exposing only the public localized value, not necessarily the whole map. Escape text for its output context instead of trusting translation values as HTML.
- Authorize a limited locale patch and validate lengths before writes. Make locale deletion distinct from a missing patch field. In
db.Transaction(ctx, func(txctx context.Context) error { ... }), read and lock the current existing model row throughtxctx, check the edited locale's expected old presence/value, and merge into that current map. Different-locale edits survive; stale same-locale edits conflict. Using the outer context can bypass the transaction. All writers need the same protocol; test SQLite-specific serialization separately. - Return errors for rollback and preserve the driver/JSON representation on encode. Avoid background goroutines using the transaction context. Publish app-owned notifications and invalidate targeted caches after commit; this is a deliberate change from upstream's pre-save event timing and requires checking listeners.
db.AfterCommitfailure does not roll back committed data. Include tenant, resource and locale in cache keys; don't mutate cached maps shared by concurrent requests.
Complete pure lookup unit; loading, corruption checks, allowed locales and authorization are outside it. It assumes a validated map with nullable string values and returns a separate presence flag so "0" is not missing:
func localized(values map[string]*string, locale, fallback string) (string, bool) {
for _, key := range []string{locale, fallback} {
if value, exists := values[key]; exists && value != nil && *value != "" {
return *value, true
}
}
return "", false
}
Acceptance checklist
- For
en: "Chair",fr: "Chaise",de: "",it: null,nl: "0", expect FrenchChaise, German/Italian/absent Portuguese fallbackChair, and Dutch0. If requested and fallback are absent, returnfalse, never a third locale. - Preserve Unicode and
pt-BRkeys. Reject unsupported locale input, malformed/scalar JSON and numeric translations. SQL/JSON null and supported legacy empty arrays follow the explicit missing-value policy without writes during reads. - Concurrent English/French updates on independent connections both persist. Same-locale stale updates conflict. Fail before commit and check original JSON plus no success notification from another connection.
- Unauthorized and cross-tenant updates leave values/caches unchanged. Locale and tenant caches cannot mix; a subsequent worker request sees the committed change without shared-map races.
- Compare source-backed merge, fallback, empty/null and event behaviour. Record deliberate differences and retain excluded features until they have replacements.
Run gofmt, go vet ./..., go test ./..., go test -race ./..., and production-driver update/concurrency integration tests. Record actual versions and outputs with the change; these checks still need to run in the destination app.
Sources
- MIT reference source:
src/HasTranslations.php,src/Translatable.php,src/Events/TranslationHasBeenSetEvent.php, andtests/TranslatableTest.php. PreserveLICENSE.mdfor adapted source. - Framework source checked:
db/tx.go; reconcile metadata with the app's module revision and use its actual JSON scanning/binding APIs. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.