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

tomasosho's avatar

blade calculation

I want to calculate this in my blade, instead its returning same values to me

{!! $i->price !!}/{!! $i->old_price !!}x100

how do i run calculations in blade?

0 likes
5 replies
tykus's avatar

First, you are printing the values of $i->price and $i->old_price, not performing a calculation. Next, this x is not a mathematical operator; it should be * for multiplication. Finally, if you can, organise your data in the Controller (or Composer) not in the View, otherwise, this would be your calculation

{{ ($i->price/$i->old_price)*100 }}
1 like
tomasosho's avatar

$i->price and $i->old_price are in a foreach loop. how do i print their values?

tykus's avatar

$i->price and $i->old_price are in a foreach loop

Can you show how you are performing the iteration currently?

how do i print their values?

Do you want to display their values or make the calculation?

tomasosho's avatar

i want to make the calculation...

		@foreach($products as $i)
                        <tr>
                            
                                <td>{{($i->price/$i->old_price)*100}}</td>

                            </td>
                        </tr>
                 @endforeach
tykus's avatar
tykus
Best Answer
Level 104

Assuming each $i is a Product instance with a price and old_price attributes, then it should be working as expected; what are you getting?

If $i (a Product?) is an Eloquent Model, you could move this logic off the Blade template into an accessor method on the Model, e.g.

// Product.php

class Product extends Model
{
	// ... other code

	public function getDiscountAttribute()
	{
		return ($this->price/$this->old_price) * 100;
	}
}

Then your view template can get the computed discount attribute on the model:

@foreach($products as $product)
	<tr>
		<td>{{ $product->discount }}</td>
	</tr>
@endforeach

I use "discount" here, but your calculation probably represents something else

1 like

Please or to participate in this conversation.