Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chriss39's avatar

Calculate a value based on two other fields before saving

I have a simple quantity field, price field and I can't figure out how to calculate a total field where I will hide it on the creating and updating. When I create a record I would like to take say quantity of 10 and price of 5 and total would be saved as 50. I know this should be easily doable but can't seem to get it to work. I tried a resolvedUsing with no luck and also a Mutator on the Model with no luck. Any tips to lead me down the right path would be appreciated. ideally without installing an outside package to accomplish it. I don't care about it showing in real time on the front end.

0 likes
7 replies
GeeBee's avatar

Are you wanting this to be automatically stored in the database? Assuming MySQL, are you thinking of something like the following?

create table prices (
	price decimal(6,2),
	quantity smallint unsigned,
	cost decimal(8,2) generated always as (price * quantity)
);

insert into prices (price, quantity) values (5.95, 10);

select * from prices;

+-------+----------+-------+
| price | quantity | cost  |
+-------+----------+-------+
|  5.95 |       10 | 59.50 |
+-------+----------+-------+
1 row in set (0.00 sec)
tomasosho's avatar

You can define your $price variable and $quantity variables. Depending on if you get them from request.

$cost = $price * quantity;

$tosave = $cost;
$tosave->save();

return redirect();
chriss39's avatar

@geebee GeeBee I am unsure how to write that in a laravel migration.

@tomasosho I could put that in a controller when a request came in but I want to do it in a Laravel Nova Resource.

Thomas Wittchen's avatar
Level 3
public static function boot()
{
    parent::boot();
    Order::saving(function (Order $order) {
         $order->total = $order->price * $order->quantity;
    });
}

in your model. hope this is what you mean

philipbaginski's avatar

I have similar question: I have a table with result of the runners. In column 'margin' I'm saving value beetween runners, in column 'total_margin' I'm saving margin beetween winner and other next runners. So, every time I edit result row, I have to input margin, and add this value to last saved value from 'total_margin', and save. I think the last value from 'total_margin' column have to be restricted to result_id. Otherwise last value will be delivered to next result. Any idea?

jcodes's avatar

@Thomas Wittchen Is there a way to use the auto-increment ID field? This is not working if I use the following:

$order->total = $order->id * $order->value;

Id is the default auto increment field. Any work around?

Please or to participate in this conversation.