0

When I use json_encode in the update query builder of laravel, it returns empty. The code I tried was this:

    DB::table('catalog_product')->update([
        'reference' => json_encode(['data' =>DB::raw('external_barcode')]),
    ]);

How do I do this?

4
  • Can you explain what you're trying to do here? Can you also give a little bit more information about the table e.g. what is reference, what is external_barcode? etc. Commented Jul 9, 2019 at 10:49
  • @RossWilson I thought it was self explainatory. I'm trying to move the data in one column to another in json format Commented Jul 9, 2019 at 10:51
  • You are mixing PHP and MYSQL update, this cannot work. You can use pure PHP and get all your records from your table, then loop and update with json_encode() function, or use JSON_OBJECT function in mysql. But you'll need key / value to encode a value. Commented Jul 9, 2019 at 10:54
  • @VincentDecaux I have updated the code in question for key value pair. How do I use the json object? Commented Jul 9, 2019 at 10:59

1 Answer 1

2

As I said, you are mixing a PHP function with a MYSQL value.

Or you use the PHP way :

$products = CatalogProduct::get();

foreach ($products as $product) {
   $product->reference = json_encode(['data' => $product->external_barcode]);
   $product->save();
}

Or using MYSQL :

DB::table('catalog_product')->update([
    'reference' => DB::raw('JSON_OBJECT("data", external_barcode)'),
]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. The 2nd method was what I needed
Accept the answer if your problem is solved. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.