简体   繁体   中英

How can insert array of multiple inputs in database?

I'm inserting an array of multiple inputs. but when i dd it or create it doesn't insert or returning any values. How can i use create in this situation? I'm new to laravel.

foreach ($data['sku'] as $key => $val) {


    $attrCountSKU = ProductsAttribute::where('sku', $val)->count();
    if ($attrCountSKU > 0) {
        return back()->with('error', 'SKU already exists for this product! Please input another SKU.');
    }

    $attrCountSizes = ProductsAttribute::where(['product_id' => $product->id, 'size' => $data['size'][$key]])->count();

    if ($attrCountSizes > 0) {
        return back()->with('error', 'Size already exists for this product! Please input another Size.');
    }


    $attribute = new ProductsAttribute;
    $attribute->product_id = $product->id;
    $attribute->sku = $val;
    $attribute->size = $data['size'][$key];


    $attribute->price = $data['price'][$key];
    $attribute->stock = $data['stock'][$key];

    dd($attribute);
    dd($attribute->create());
}

You need to save the model, using the save() method.

Add this after setting all the attributes:

$attribute->save();

return $attribute->id // Will be set as the object has been inserted

You could also use the create() method to create and insert the model in one go:

$attribute = ProductsAttribute::create([
    'product_id' => $product->id,
    'sku' => $val,
    'size' => $data['size'][$key],
    'price' => $data['price'][$key],
    'stock' => $data['stock'][$key],
]);

Laravel Docs: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models

Instead of $attribute->create() you should use $attribute->save() method.

Or with the create() method you can do like this

$flight = ProductsAttribute::create(
    [
        'product_id' => $product->id,
        'sku' => $val,
        'size' => $data['size'][$key],
        'price' => $data['price'][$key],
        'stock' => $data['stock'][$key],            
    ]
);

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