0

I am working on inserting a JSON object in JSON-type MySQL column.

Sample data that I am trying to insert is like this:

sample data

Sample Laravel code

public function store(Request $request)
{
    $layaway = new Layaway;

    foreach($request->selected_products as $p) {
        $layaway->selected_products = json_encode([
            'id' => $p['id'],
            'sku' => $p['sku'],
            'name' => $p['name'],
            'image' => $p['image'],
            'description' => $p['description'],
            'category_id' => $p['category_id'],
            'regular_price' => $p['regular_price']
        ]);

    }

    $layaway->save();

    return response()->json([
        'success' => true,
        'message' => 'Layaway Program has been successfully saved!'
    ]);

}

Sample response from dd()

sample result

Question How can I save all of the data in the $request->selected_products into my MYSQL json-type column?

2
  • 1
    why don't just json_encode($request->selected_products) and then save it to $layaway->selected_products? saves you a for loop. Commented Oct 12, 2018 at 0:13
  • Thank you. it is working. I don't know that it is just as easy as that. silly me. Commented Oct 12, 2018 at 1:32

1 Answer 1

2

As said in the comment by Wreigh,

I just changed this code:

foreach($request->selected_products as $p) {
    $layaway->selected_products = json_encode([
        'id' => $p['id'],
        'sku' => $p['sku'],
        'name' => $p['name'],
        'image' => $p['image'],
        'description' => $p['description'],
        'category_id' => $p['category_id'],
        'regular_price' => $p['regular_price']
    ]);

}

into this code:

$layaway->selected_products = json_encode($request->selected_products);

Thank you.

Sign up to request clarification or add additional context in comments.

Comments

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.