Laravel Mass update using foreach loop

Viewed 561

I was trying to mass update the record with the same foreign key. But I encounter a problem. If I use

 $products = $products::findorfail($prod_id);

It manages to update a single column. Then when I trying using

$products = $products::query()->where('product_id', $prod_id)->get();

I encounter "Method Illuminate\\Database\\Eloquent\\Collection::options does not exist.", How do I overcome this problem.

Here is my current code


    public function update(array $data = [],  $prod_id, Variation $products)
    {

        foreach ($data['variants'] as $product) {
            $products = $products::query()->where('product_id', $prod_id)->get();

            $products->options()->detach(($product['option_id']));
            $products->options()->attach(($product['option_id']));
            $products->fill(Arr::set($data, 'product_id', $prod_id));
            $products->fill(Arr::only($product, $products->getFillable()));
        }


        return $products->save();
    }

Thanks in advance.

1 Answers

You should get first() method to the one instance of the Product model and then attach or detach it to other things. Additionally, you can pass an array to attach or detach method for creating or removing relationship, so first gather the ids then pass them to these methods.

foreach ($data['variants'] as $product) {
    $option_ids[] = $product['option_id'];
}

$product = $products::query()
    ->where('product_id', $prod_id)
    ->first();

$product->options()->detach($option_ids);
$product->options()->attach($option_ids);
$product->fill(Arr::set($data, 'product_id', $prod_id));
$product->fill(Arr::only($product, $product->getFillable()));
Related