Getting and setting translations | laravel-translatable-go | Spatie       

 SPATIE  

laravel-translatable-go
=======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-translatable-go](https://spatie.be/docs/laravel-translatable-go/v1)  Basic-usage  Getting and setting translations

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-translatable-go/v1) 

  Getting and setting translations    
- [ Introduction ](https://spatie.be/docs/laravel-translatable-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-translatable-go/v1/requirements)
- [ Upgrading ](https://spatie.be/docs/laravel-translatable-go/v1/upgrading)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-translatable-go/v1/installation-setup)
- [ Testing ](https://spatie.be/docs/laravel-translatable-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-translatable-go/v1/releasing)
- [ Questions and issues ](https://spatie.be/docs/laravel-translatable-go/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-translatable-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-translatable-go/v1/support-us)
- [ About us ](https://spatie.be/docs/laravel-translatable-go/v1/about-us)

Basic usage
-----------

- [ Getting and setting translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/getting-and-settings-translations)
- [ Removing translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/removing-translations)
- [ Replacing translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/replacing-translations)
- [ Querying translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/querying-translations)
- [ Validating translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/validating-translations)
- [ Handling missing translations ](https://spatie.be/docs/laravel-translatable-go/v1/basic-usage/handling-missing-translations)

Advanced usage
--------------

- [ Available events ](https://spatie.be/docs/laravel-translatable-go/v1/advanced-usage/available-events)
- [ Customize the toArray method ](https://spatie.be/docs/laravel-translatable-go/v1/advanced-usage/customize-the-toarray-method)
- [ Usage with factories ](https://spatie.be/docs/laravel-translatable-go/v1/advanced-usage/usage-with-factories)

 Getting and setting translations
================================

###  On this page 

1. [ Setting a translation ](#content-setting-a-translation)
2. [ Getting a translation ](#content-getting-a-translation)

First, prepare your model as instructed in [the installation instructions](../installation-setup).

Setting a translation
-----------------------------------------------------------------------------------------------------------------------

The easiest way to set a translation for the current locale is to use `SetAttribute`:

```
translations := translatable.For(&newsItem, *translatable.From(ctx)).UsingLocale("nl")
if err := translations.SetAttribute(ctx, "name", "Nieuwe vertaling"); err != nil {
    return err
}
```

To actually save the translation, don't forget to save your model:

```
if err := model.Save(ctx, &newsItem); err != nil {
    return err
}
```

You can immediately set translations when creating a model:

```
newsItem := models.NewsItem{
    Name: db.NewJSON[any](map[string]any{
        "en": "Name in English",
        "nl": "Naam in het Nederlands",
    }),
}
if err := model.Create(ctx, &newsItem); err != nil {
    return err
}
```

Direct struct initialization stores raw values without translation mutators or translation-set events. Use the setter before `model.Create` when you need those hooks.

For a specific locale, use `SetTranslation(ctx, "name", "en", "Hello")`. To set multiple languages, use `SetTranslations(ctx, "name", map[string]any{"en": "Hello", "es": "Hola"})`. Check the returned error before saving.

`SetTranslations` merges locales. An empty map clears the field. `SetAttribute` treats a `map[string]any` as a locale map. A scalar or nonempty `[]any` is a value for the current locale. An empty `[]any` clears translations. To store an object as one locale's value, call `SetTranslation` explicitly.

Getting a translation
-----------------------------------------------------------------------------------------------------------------------

Use `GetAttribute(ctx, "name")` for the current locale or `GetTranslation(ctx, "name", "nl", true)` for an explicit locale. The boolean allows fallback. Pass false to request an exact locale. Go does not intercept ordinary struct field access and does not duplicate PHP's `translate` aliases.

### Getting all translations

`GetTranslations("name", nil)` returns all raw values that pass null/empty filtering. Pass `[]string{"en", "fr"}` as the second argument to select languages. A non-nil empty slice selects no languages.

`AllTranslations(nil)` returns maps for every translatable attribute. Accessors are not applied to these raw maps. Maps are shallow copies, so nested object/list values still refer to the model's values. Treat returned nested values as read-only, or copy them before editing.

### Get locales that a model has

`Locales()` returns the sorted union of locales across attributes. `TranslatedLocales("name")` returns the sorted locales for one attribute. `HasTranslation("name", "nl")` checks an exact locale without fallback, excluding null even when null reads are enabled. An empty locale in `HasTranslation` uses the current locale.

### Nested JSON fields

Declare `meta->description` in `TranslatableAttributes`. Use that complete key in getters and setters. Nested writes preserve sibling fields, including clearing a nested locale map.

### Custom accessors and mutators

Implement optional interfaces on your model:

```
func (n *NewsItem) MutateTranslation(ctx context.Context, key, locale string, value any) (any, error) {
    if text, ok := value.(string); ok {
        return strings.TrimSpace(text), nil
    }
    return value, nil
}

func (n *NewsItem) AccessTranslation(key string, value any) (any, error) {
    return value, nil
}
```

Mutators run before storage and events. An error rejects that value. Accessors run on single-value reads and presentation serialization, not raw persistence. They can read other model fields. Bulk mutations run in lexical locale order and are not atomic. Earlier changes remain if a later hook fails. Models and views are not safe for concurrent mutation without application synchronization.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
