Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ash92's avatar
Level 1

Sum two fields in the same table.

I have a table named bills. in the table one field is amount and another field is bill_amount_left. I want to sum up the bill_amount_left when a new bill is added. If a bill is created against an user then, users previous bill_amount_left will be automatically increased with the new bill. How to do that?

    $data = $this->validate([
        'property_id' => 'required',
        'amount' => 'required',
        'due_date' => 'required',
        'start_date' => 'required',
        'end_date' => 'required',
        'bill_type' => 'required',
        'remark' => 'required',

    ]);
    $data['amount_left'] = $data['amount'];        
    $bill = Bill::create($data);

I am using these code to create a bill. So, I need to update the amount_left field every time a new bill is created. Also I need to identify against which property they bill is created. For example a bill is created against property_id 1. Then another bill created against property_id 1. So the field amount_left should automatically increased with newly created bill.

0 likes
8 replies
SilenceBringer's avatar
Level 55

@ash92 if I understand the question correctly, you can create observer https://laravel.com/docs/9.x/eloquent#observers and watch creating event

    public function creating(Bill $bill)
    {
		if ($previousBill = Bill::where('property_id', $bill->property_id)->latest('id')->first()) {
			$bill->bill_amount_left = $previousBill->bill_amount_left + $bill->amount;
		}
    }
1 like
Ash92's avatar
Level 1

@SilenceBringer Thanks for your reply. Your code worked. But I wanted to do like update previous record also. For example I have a bill for property1 previously 1000$. Now I will add another bill against same property and bill_amount_left field of record one also needed to update. Is it possible ? or it is best practice to update latest record and keep old one as it is for future reference? Thank you again.

SilenceBringer's avatar

@Ash92 hmm... add created event

    public function creating(Bill $bill)
    {
		if ($previousBill = Bill::where('property_id', $bill->property_id)->latest('id')->first()) {
			$bill->bill_amount_left = $previousBill->bill_amount_left + $bill->amount;
		}
    }

    public function created(Bill $bill)
    {
		Bill::where('property_id', $bill->property_id)->update('bill_amount_left ', $bill->bill_amount_left );
    }
1 like
Ash92's avatar
Level 1

@SilenceBringer SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' this is the error if i use the code.

SilenceBringer's avatar

@Ash92 Oops

    public function created(Bill $bill)
    {
		Bill::where('property_id', $bill->property_id)->update(['bill_amount_left' => $bill->bill_amount_left]);
    }

Please or to participate in this conversation.