sahar_mkr's avatar

saving some models

Hi everyone, I have a transaction and transactionLog model when a transaction happens, I want to save both transaction and transactionLog in the table, I get all the information of transaction and transactionLog from the request, for example, in the transactioLog table I have provience_name, but I don't have this column in transaction table, can I use the boot method in the transaction model in order to save the transactionLog when a transaction happens? how can I do that?

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, you can use the boot method in the Transaction model to save the TransactionLog when a Transaction happens. Here's an example implementation:

class Transaction extends Model
{
    protected $fillable = ['amount', 'description'];

    protected static function boot()
    {
        parent::boot();

        static::created(function ($transaction) {
            $transactionLog = new TransactionLog([
                'transaction_id' => $transaction->id,
                'amount' => $transaction->amount,
                'description' => $transaction->description,
            ]);
            $transactionLog->save();
        });
    }
}

In this example, we're using the created event to automatically create a new TransactionLog record whenever a new Transaction is created. We're also assuming that the TransactionLog model has a transaction_id foreign key to link it to the Transaction.

Note that this implementation assumes that you're using Eloquent to save your models. If you're using a different ORM or database library, you'll need to adjust the code accordingly.

Please or to participate in this conversation.