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
try using created instead of saving
When a new model is saved for the first time, the
creating
andcreated
events will fire. If a model already existed in the database and thesave
method is called, theupdating
/updated
events will fire. However, in both cases, thesaving
/saved
events will fire.$order->id
is exists now.