Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

magero's avatar

MYSQL JSON UPDATE STATEMENT

Hi LaraFam, i am trying to write an update statement for a json column with a where clause which is also part of the json .

''' [{"id": 1, "code":"1234", "name":"pen", "status":"in-store" }] '''

As listed above, i would like to update status where code submitted from the form is same as code in the json column.

Anyone know what is the correct mysql update statement with the where clause being part of the json? Please help

0 likes
6 replies
lostdreamer_nl's avatar
// where clause on json field
$redLovers = DB::table('users')
    ->where('meta->favorite_color', 'red')
    ->get();

// update on a json field
DB::table('users')
    ->where('id', 1)
    ->update(['meta->wants_newsletter' => false]);
magero's avatar

@LOSTDREAMER_NL - The first section of the code doesn't have an update function and the where clause on the second update function is not querying a json column

staudenmeir's avatar

What do you mean by "where code submitted from the form is same as code in the json column"? Can you provide an example?

magero's avatar

@STAUDENMEIR - I have a json type column which stores inputs from a create item form in the format shown

[{"id": 1, "code":"1234", "name":"pen", "status":"in-store" }]

what i want is to update the status section to sold where the code sent from another form matches the one in the json element i.e 1234

Here is the code i have tried but returns false

''' $update = DB::update(DB::raw('UPDATE codes SET items_code = JSON_SET(items_code, "$.item_status", "sold") WHERE items_code->"$.code" = "$value"; '));

'''

staudenmeir's avatar

I don't think that's possible with a single SQL query.

lostdreamer_nl's avatar

@magero, then throw the 2 together.... come one, programming is about solving problems right?

// update on a json field
DB::table('codes')
    ->where('items_code->code', request()->code)
    ->update(['items_code->status' => 'sold']);

// or ofcourse by model
Code::where('items_code->code', request()->code)
    ->update(['items_code->status' => 'sold']);

Please or to participate in this conversation.