简体   繁体   中英

Inserting JSON object in MySQL in Laravel

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 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()

样本结果

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM