'Method Collection::save does not exist while trying to update data dynamically

I have a form at Blade like this:

<form role="form" method="POST" action="{{ route('products.post.vars', $product->id) }}">
    @csrf
    @foreach($attributes as $attribute)

    <div class="form-group">
          <label for="var_{{$loop->index+1}}">Price</label>
          <input class="form-control" type="text" name="var_{{$loop->index+1}}" value="" class="form-control" id="var_toman_{{$loop->index+1}}">
    </div>
</form>

An now in order to submit this data and update records in table, I coded this:

            try{
                $attributes = AttributeProduct::where('product_id',$product->id)->where('attribute_changeable',1)->get();
    
                for($i=0;$i<count($attributes);$i++){
                    $iterator = $i + 1;
                    $attributes[$i]->product_price = $request->input("var_$iterator");
                    $attributes->save();
                }
            }
            catch (\Exception $e) {
                dd($e->getMessage());
            }

But now I get this error:

Method Illuminate\Database\Eloquent\Collection::save does not exist.

So whats going wrong here? How can I fix this issue?



Solution 1:[1]

You need to save the currant attribute by using $attributes[$i]->save();

try{
                $attributes = AttributeProduct::where('product_id',$product->id)->where('attribute_changeable',1)->get();
    
                for($i=0;$i<count($attributes);$i++){
                    $iterator = $i + 1;
                    $attributes[$i]->product_price = $request->input("var_$iterator");
                    $$attributes[$i]->save();
                }
            }
            catch (\Exception $e) {
                dd($e->getMessage());
            }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wael Khalifa