Installation &amp; setup | laravel-translatable-rust | Spatie       

 SPATIE  

laravel-translatable-rust
=========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-translatable-rust](https://spatie.be/docs/laravel-translatable-rust/v1)  Installation &amp; setup

 Version   v1      

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

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

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

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

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

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

 Installation &amp; setup
========================

###  On this page 

1. [ Making a model translatable ](#content-making-a-model-translatable)
2. [ Configuration ](#content-configuration)
3. [ Custom models ](#content-custom-models)

This package uses `laravel-rust` 0.1.0 and Rust 1.99+. Install from Git; the crate is not published to crates.io.

```
[dependencies]
laravel = { package = "laravel-rust", version = "=0.1.0", default-features = false, features = ["database-sqlite"] }
spatie-laravel-translatable = { git = "https://github.com/spatie/laravel-translatable-rust", branch = "main" }
serde_json = "1"
```

Making a model translatable
-----------------------------------------------------------------------------------------------------------------------------------------

Use the real model macro and JSON cast. Each translatable column contains a locale map. The two reference methods connect the package to your typed model fields; they do not implement persistence.

```
use laravel::db::Json;
use laravel::model::model;
use spatie_translatable::{Error, HasTranslations, Result, Value};

#[model]
pub struct NewsItem {
    pub id: i64,
    pub name: Json<Value>,
    pub meta: Json<Value>,
}

impl HasTranslations for NewsItem {
    const TRANSLATABLE: &'static [&'static str] = &["name", "meta->description"];

    fn translation_attribute(&self, column: &str) -> Option<&Value> {
        match column {
            "name" => Some(&self.name.0),
            "meta" => Some(&self.meta.0),
            _ => None,
        }
    }

    fn translation_attribute_mut(&mut self, column: &str) -> Result<&mut Value> {
        match column {
            "name" => Ok(&mut self.name.0),
            "meta" => Ok(&mut self.meta.0),
            _ => Err(Error::UnknownColumn(column.into())),
        }
    }
}
```

Create JSON columns with a real migration:

```
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema().create("news_items", |table| {
        table.id();
        table.json("name");
        table.json("meta");
    }).await
}
```

Register the directory with `Application::configure().with_migrations(laravel::db::migrations!("database/migrations"))`. Run `migrate` before querying the model. The [complete example](https://github.com/spatie/laravel-translatable-rust/blob/main/examples/news.rs) shows boot, migrations, creates, updates, and reloads.

Configuration
-----------------------------------------------------------------------------------------------

```
use laravel::{Application, config::Env};
use spatie_translatable::{Translatable, service_provider};

let app = Application::configure()
    .replace_env(Env::default())
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_config(|config, _| {
        config.set(Translatable { locale: "nl".into(), ..Default::default() });
    })
    .create();
```

For request-specific locale changes, clone the settings value rather than the container's shared `Inject` handle:

```
let mut settings = (*app.resolve::<Translatable>().await).clone();
settings.locale = "fr".into();
```

The provider preserves a typed section registered by an earlier provider. Application `with_config` callbacks run afterward and can replace it. The container resolves the final settings lazily; `with_services` can override the binding too.

Environment defaults use the native `Env` parser and validation:

- `APP_LOCALE` defaults to `en`.
- `APP_FALLBACK_LOCALE` defaults to `en`.
- `TRANSLATABLE_FALLBACK_LOCALE` selects an optional package fallback.
- `TRANSLATABLE_FALLBACK_ANY` defaults to `false`.
- `TRANSLATABLE_ALLOW_NULL` defaults to `false`.
- `TRANSLATABLE_ALLOW_EMPTY_STRING` defaults to `false`.
- `TRANSLATABLE_LOCALES` is a comma-separated list of search locales. Whitespace and empty entries are removed.

Callbacks belong in application code, not environment variables. The framework has no application translator service; the typed settings and per-view locale remain explicit.

Custom models
-----------------------------------------------------------------------------------------------

`HasTranslations` works on your application's own native model. Keep custom fields, table names, and connections in `#[model]`, for example `#[model(table = "articles", connection = "content")]`. Register that connection with the framework's database configuration. Translation setters only edit the selected model's JSON columns; its native create, update, and query builders retain its connection.

Override the trait's `get_fallback_locale`, `use_fallback_locale`, `mutate_translation`, or `access_translation` methods for model-specific behavior. There is no package model, background job, model-class config key, or queue connection to override.

 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)
