Search code examples
phplaravellaravel-8laravel-9

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

  • You need to specify the index you are saving data to

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