简体   繁体   中英

how to automatically update one table column by another table column update in laravel

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM