Calculate a value based on Auto Increment ID & other field before saving
Hello, 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;
});
}
(above is a dummy example, just to iterate the kind of results required).
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.
why you do this $order->id * $order->quantity code? isn't it mean you will have a not very suitable result. assume there an id increment 50 * 2, isn't the total order is 100. user just want order 2 not 100
nah, if that the case just change the saving with creating
using the creating event, you ensure that the total attribute is calculated using the auto-increment ID and the quantity attribute just before the record is saved
public static function boot()
{
parent::boot();
Order::creating(function (Order $order) {
$order->total = $order->id * $order->quantity;
});
}
the unique_id must not nullable,
but you can try to override the save method in the Order model. if the model doesn't exist (i.e., it's a new record being created), calculate the total value based on the quantity and the auto-incremented id. then, call the parent save method to perform the actual record insertion.
this is the reference
class Order extends Model
{
public function save(array $options = [])
{
if (!$this->exists) {
$this->total = $this->quantity * $this->id;
}
parent::save($options);
}
}
and call the insert/save data in controller like this
$order = new Order();
$order->quantity = 10; // set the quantity value
// the 'total' attribute will be calculated automatically based on the 'id' and 'quantity' in the overridden save method.
$order->save(); // Save the record to the database