Laravel Rust✓ Human-reviewed

One app-owned JSON attribute in Laravel Rust

Extract one literal JSON key with explicit keep/set/forget semantics, preserved siblings and guarded concurrent persistence.

Approved 2026-12-04T15:00:07.518549Z · Submission 103

One app-owned JSON attribute in Laravel Rust

Scope

Replace one model's literal theme key read/set/forget behavior with explicit JSON-object handling. Keep sibling keys intact. Exclude dot/wildcard paths, arbitrary collection forwarding, dynamic query scopes, arrays as root values and general package API emulation. Preserve Spatie's MIT notice for adapted source. At the time of writing the catalog listed a community Rust port; check get-recipe's current port catalog before extraction. This guidance has not been exercised in your app; verify it below.

Source behaviour

src/SchemalessAttributes.php wraps raw model JSON in a collection, get uses data_get, set handles iterable merge or data_set, and forget uses Arr::forget. override assigns data back to the model but does not save it. Raw non-array decoded values fall back to an empty array. src/Casts/SchemalessAttributes.php serializes supported values and can turn non-array values into null; it is not simply a JSON-object cast. tests/HasSchemalessAttributesTest.php checks saved types, defaults, dotted/wildcard access and forgetting.

This recipe deliberately requires a stored JSON object instead of silently normalizing invalid roots, treats theme as one literal key and preserves an empty object as {}. A present JSON null is not a missing key and Set(None) is not removal. Audit historical rows and consumers before adopting these deliberate restrictions.

Implementation

  1. Inventory actual keys/types/defaults, SQL null versus JSON null, whole-map replacement, mutations and query scopes. Capture original read/JSON output fixtures. Keep excluded callers package-backed until separately replaced.
  2. At the existing request/action boundary validate operation, content type, size, string length and allowed theme values. Derive actor/tenant and authorize the model/field; do not let input select a JSON path or overwrite the whole map. Choose keep/set/forget explicitly instead of collapsing null into deletion.
  3. Use an object-preserving JSON representation. The pure function below clones the stored object, changes only theme and rejects incompatible roots; it does not load/save/authorize. Keep unknown siblings internally and allowlist response fields rather than exposing the full map.
  4. Load the authorized row under the existing transaction/row lock, apply the change and save on that connection, or use a verified optimistic-version compare-and-swap with stale-write failure. A transaction around a stale preloaded whole object does not prevent lost updates. Check affected-row/save results and preserve rollback, observers and post-commit invalidation. Concurrent edits to different keys must not overwrite each other.
  5. Preserve JSON numeric/boolean/null values and avoid unrequested migrations/caches. Do not assume a framework JSON wrapper implements upstream dot/wildcard/default semantics. Reconcile the metadata refs with the actual app's lockfile.

Complete pure transformation, assuming serde_json is already available. Map operation names from the validated boundary to this enum; it intentionally has no arbitrary JSON path:

use serde_json::Value;

enum ThemeChange {
    Keep,
    Set(Option<String>),
    Forget,
}

fn patch_theme(stored: &Value, change: ThemeChange) -> Result<Value, &'static str> {
    let mut object = stored.as_object().ok_or("stored value must be object")?.clone();
    match change {
        ThemeChange::Keep => {}
        ThemeChange::Set(value) => {
            object.insert("theme".into(), value.map(Value::String).unwrap_or(Value::Null));
        }
        ThemeChange::Forget => { object.remove("theme"); }
    }
    Ok(Value::Object(object))
}

Acceptance checklist

  • Starting with {"theme":"dark","density":0,"enabled":false,"nested":{"x":1}}, keep preserves everything; setting "0" or empty string preserves those strings; setting null keeps a present null key; forgetting removes only theme. Original input remains unchanged.
  • Forgetting the only key produces {}, not [] or null. Reject stored null, array, number or string through the explicit corruption policy; compare that deliberate difference with existing consumers.
  • Test missing versus present-null reads using key presence, not only Option<String>. Preserve defaults and output omissions where callers rely on them. Rejected operation/validation input must not persist any change.
  • Run two actual database sessions updating different keys and require both survive, or require an explicit stale-write error. Test unauthorized/cross-tenant writes, rollback, failed persistence and post-commit/cache behavior.
  • Search casts, dotted paths, collection forwarding and query scopes before dependency removal. Run cargo test plus request/persistence tests on the real driver and record exact outputs/versions.

Sources

  • MIT reference: src/SchemalessAttributes.php, src/Casts/SchemalessAttributes.php, tests/HasSchemalessAttributesTest.php, LICENSE.md.
  • Framework source checked: database transaction boundary and crates/http/src/http/json.rs. JSON decoding alone does not implement a write-lock policy.
  • Port options: check get-recipe's current port catalog (sourced from Package Port) at implementation time.