One app-owned JSON attribute in Laravel PHP
Scope
Inline one model's literal theme keep/set/forget operations over a JSON object. Preserve unrelated keys. Exclude dotted/wildcard paths, collection method forwarding, dynamic model scopes, list roots and arbitrary whole-map replacement. Preserve Spatie's MIT notice when adapting source. Check get-recipe's current port catalog before choosing an alternative. This guidance has not been exercised in your app; verify it below.
Source behaviour
src/SchemalessAttributes.php wraps raw JSON in a collection, falls back to an empty array for non-array roots, uses data_get/data_set and Arr::forget, and assigns changes back to the model without saving. Iterable set merges values; it is not identical to one key assignment. src/Casts/SchemalessAttributes.php accepts some encoded JSON values and normalizes non-array results to null. tests/HasSchemalessAttributesTest.php exercises defaults, persistence, types and dotted/wildcard paths.
This recipe deliberately requires a JSON object decoded as \stdClass, treats the key literally, rejects incompatible roots at decoding, and keeps an empty map as {}. That differs from the package's array-oriented fallback. A present null key is not a missing key. Check root/output consumers before adopting these restrictions.
Implementation
- Inventory keys/defaults, stored SQL null/JSON null, whole-map replacement, path/query/collection callers and emitted JSON. Capture fixtures first. Keep excluded behavior package-backed; a native
arraycast is not a drop-in replacement for the wrapper. - Validate the bounded operation, string length/theme allowlist and request shape at the existing boundary. Derive trusted actor/tenant and authorize field edits. Never permit a request to select arbitrary paths or mass-assign the stored attribute map.
- Decode the stored JSON once with
JSON_THROW_ON_ERRORand require\stdClass; do not convert every root to associative arrays, which loses empty object/list distinctions. The pure helper below shallow-clones the object and changes one literal property. Nested siblings remain shared read-only and must not be mutated through the result. - Load the authorized model inside the correct connection's row-locked transaction, then patch and save, or preserve optimistic version checking with stale-write rejection. A transaction around a stale preloaded object still loses concurrent sibling edits. Reconcile the chosen native/custom cast's write encoding; do not double-encode JSON. Throw if an Eloquent save is vetoed with false so related changes roll back.
- Preserve observer/post-commit behavior and cache invalidation after commit. Return only authorized projected keys. No new schema/cache is needed. Remove package casts/scopes only once every dependent caller has an equivalent path.
Complete pure top-level transformation, with fully qualified names suitable inside an application namespace. set with null stores a property; forget removes it. This does not authorize or persist anything:
function patchTheme(\stdClass $stored, string $operation, ?string $value = null): \stdClass
{
$next = clone $stored;
switch ($operation) {
case 'keep': break;
case 'set': $next->theme = $value; break;
case 'forget': unset($next->theme); break;
default: throw new \InvalidArgumentException('unknown operation');
}
return $next;
}
Acceptance checklist
- From
{"theme":"dark","density":0,"enabled":false,"nested":{"x":1}}, keep preserves all, string"0"/empty string remain strings, set null creates a present null property, and forget removes only theme. Useproperty_exists, notisset, for presence. The original top-level input remains unchanged. - Forget the sole property and require encoded
{}. Reject stored null/list/scalar/malformed JSON through the explicit data-integrity policy; compare this deliberate difference against historical consumers. Reject unknown operations before saving. - Confirm encoding through the actual model cast and reload from the real database; no double encoding or accidental numeric-key/list conversion. Preserve defaults/output projections and keep private siblings out of responses.
- In two database sessions update different keys and require both survive or explicit stale-write rejection. Exercise cross-tenant denial, observer veto, rollback and post-commit cache failure without replaying a committed write.
- Search dot/wildcard/collection/query/cast consumers and
composer why spatie/laravel-schemaless-attributesbefore removal. Run actual request/model tests and record versions and decisive outputs.
Sources
- MIT reference:
src/SchemalessAttributes.php,src/Casts/SchemalessAttributes.php,tests/HasSchemalessAttributesTest.php,LICENSE.md. - Framework source checked:
src/Illuminate/Database/Eloquent/Model.php, attribute casting andsrc/Illuminate/Database/Concerns/ManagesTransactions.php. Reconcile lockfile, actual cast and driver. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.