How do i make discount percentage of products in Laravel

1.7k Views Asked by At

I want to show a discount percentage of my products.

I get this error:

Division by zero (0)

Can anyone suggest me that what's I'm doing wrong ?

@foreach ($Products as $product)
            <div>
                <span>{{ (($product->promo_price/$product->original_price) * 100) }}% <br />OFF</span>
                <img src="{{ asset('/storage/'.$product->image) }}" />
            </div>
            <div>
                <h2>{{ $product->title }}</h2>

                    <ins>  
<span>{{ $product->original_price }}DHs</span>
{{ $product->promo_price}}Dhs   
</ins>
            </div>
@endforeach
2

There are 2 best solutions below

2
AntoineB On BEST ANSWER

The error is due to the fact that you have the original_price of some products equal to 0 or null.

You have to check before printing the discount to see if they have an original_price:

@foreach ($Products as $product)
    <div>
        @if ($product->original_price)
        <span>{{ (($product->promo_price/$product->original_price) * 100) }}% <br />OFF</span>
        @endif
        <img src="{{ asset('/storage/'.$product->image) }}" />
    </div>

    <div>
        <h2>{{ $product->title }}</h2>

        <ins>  
            <span>{{ $product->original_price }}DHs</span>
            {{ $product->promo_price}}Dhs   
        </ins>
    </div>
@endforeach

I added a condition on line 3 that will display the <span> with the discount only if you have an original_price for the product, and it is not equal to 0.

1
Leonardo Rossi On

The error is self-suggesting: You are dividing by zero, which is not allowed in ordinary arithmetic.

Check that $product->original_price has a value before using that as denominator, probably it is 0 or null