Error: "Method IlluminateDatabaseEloquentCollection::update does not exist." How do I update multiple row of data to table? [Eloquent]

  eloquent, laravel, laravel-8, php

So I have this

        $master_item_id = array_map('intval', $request->master_item_id);
        $quantity = array_map('intval', $request->quantity);
        $price = MasterItem::whereIn('id', $master_item_id)->get('price');

        foreach ($master_item_id as $key => $no) {
            $input['price'] = $price[$key]['price'];
            $input['quantity'] = $quantity[$key];
            $subtotal[] = $input['price'] * $input['quantity'];
        }

        $total_price = array_sum($subtotal);

        // Update transaction
        $transaction = Transaction::find($id);
        $transaction->total_price = $total_price;
        $transaction->last_edited_by = Auth::user()->name;
        $transaction->update();

        // Update transaction_item
        foreach ($master_item_id as $key => $no) {
            $transaction = Transaction::find($id);
            $transaction->transaction_item->transaction_id= $transaction->id;
            $transaction->transaction_item->master_item_id = $no;
            $transaction->transaction_item->quantity = $quantity[$key];
            $transaction->transaction_item->price = $price[$key]['price'];
            $transaction->transaction_item->update();
        }

My Model

    // Transaction Model
    public function transaction_item()
    {
        return $this->hasMany(TransactionItem::class, 'transaction_id');
    }
    public function item()
    {
        return $this->belongsToMany(MasterItem::class, 'transaction_item', 'transaction_id', 'master_item_id');
    }
    // TransactionItem Model
    public function transaction()
    {
        return $this->belongsToMany(Transaction::class, 'transaction_id');
    }
    public function item()
    {
        return $this->belongsToMany(MasterItem::class, 'master_item_id');
    }
    // MasterItem Model
    public function transaction_item()
    {
        return $this->hasMany(TransactionItem::class, 'master_item_id');
    }

My table structure

transaction: id(pk), total_price
transaction_item: id(pk), transaction_id(fk), master_item_id(fk), quantity, price
master_item: id(pk), item_name, price

When I try to update it popped up error

Method IlluminateDatabaseEloquentCollection::update does not exist.

And the error highlighted this line of my code

$transaction->transaction_item->update();

How do I edit/update multiple rows of data? And is my relationship in my model correct? Thanks!

Source: Ask PHP

LEAVE A COMMENT