skip to Main Content

the use case is where I want to generate a calculated value using the auto-increment ID and another column to set a column value at the time of record insert.

Here is the code I am using:

public static function boot()
{
    parent::boot();
    Order::saving(function (Order $order) {
         $order->total = $order->id * $order->quantity;
    });
}

(it a dummy use case, actual column and logic is remove to ease of understanding).

The above code doesn’t work with ID field since this is the default auto increment field, but it works fine with the other columns.

Can anyone suggest a solution here?

2

Answers


  1. try using created instead of saving

    Login or Signup to reply.
  2. When a new model is saved for the first time, the creating and created events will fire. If a model already existed in the database and the save method is called, the updating / updated events will fire. However, in both cases, the saving / saved events will fire.

    public static function boot()
    {
        parent::boot();
        Order::created(function (Order $order) {
             $order->total = $order->id * $order->quantity;
        });
    }
    

    $order->id is exists now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search