Store JSON with Laravel updateOrInsert Without Array Conversion Errors

Last updated: November 29, 2026.

When Laravel updateOrInsert() creates a missing row, a PHP array supplied as a column value may fail to bind. Encode the array to JSON before passing it to the query builder so the insert and update branches receive the same value type.

<?php

use Illuminate\Support\Facades\DB;

// Run inside a bootstrapped Laravel application.
$orderId = 42;
$options = ['gift_wrap' => true, 'notes' => ['Pack separately']];
$payload = json_encode($options, JSON_THROW_ON_ERROR);

DB::table('order_preferences')->updateOrInsert(
    ['order_id' => $orderId],
    ['options' => $payload]
);

Match the write path to the column

The example assumes one preferences row per order, with a unique key on order_id and a JSON column or text column sized to hold the document. Encode the data once. JSON_THROW_ON_ERROR stops the write if the value contains invalid UTF-8 or otherwise cannot be encoded. Pass an array to json_encode() and a string to the query builder.

Calling a forwarded query-builder method through a model name can look like Eloquent attribute assignment. To use model casts instead, define an Eloquent array cast and use a model-based save such as updateOrCreate() with mass-assignment rules configured. Pass the original array on that path. Pre-encoding it risks storing a JSON string where the application expects an object or list.

Verify the missing-row case

In a disposable database, start with no row for the key and run the example. Fetch and decode the stored value, then change one option and run it again. Confirm the database still contains one row for the key and that the second read contains the new array value. A successful update on a pre-existing row does not exercise the insert path.

For concurrent writers, keep the unique constraint and consider the database-backed Laravel upsert() API. updateOrInsert() checks for an existing row before choosing a write, leaving room for competing inserts.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov