Home > other >  how to automatically update one table column by another table column update in laravel
how to automatically update one table column by another table column update in laravel

Time:07-23

I have a WALLET table with a Balance Column & I have a PAYMENT table with a Price Column I want to automatically the WALLET BALANCE Column update When the PAYMENT PRICE Column is updated or NEW PAYMENT is Created. What Should I Do?

CodePudding user response:

In laravel you can use Observers, please see this

observer code sample:

<?php

namespace App\Observers;

use App\Models\Payment;

class PaymentObserver
{
    public function created(Payment $payment)
    {
        $wallet = $payment->wallet;
        $wallet->balance = $payment->price;
        $wallet->save();
    }

    public function updated(Payment $payment)
    {
        if($payment->wasChanged('price')){
            $wallet = $payment->wallet;
            $wallet->balance = $payment->price;
            $wallet->save();
        }
        
    }
}

  • Related