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

MahmoudMonem's avatar

How can I get the percentage of discount between 2 prices in Controller

I have products table that has 2 columns price_before | price_after

In the view I loop through all products

@foreach($products as $product)

{{$product->price_before}}
{{$product->price_after}}

@endforeach

I would like to get the percentage and achieve an equation like

(1 - New Price / Old Price)*100)

so that it looks 50% or at least 50 .. not like 50.1234223

my ProductsController.php

public function index(){
$products = Product::orderBy('created_at','desc')->paginate(39);
return view('products', ['products' => $products]);
}

How can I achieve that in the productscontroller ?

0 likes
6 replies
jlrdw's avatar

Definitely look up the math functions in the PHP manual, all sorts of functions there you may need.

Using a framework such as laravel goes hand-in-hand with using PHP functions as needed.

1 like
MahmoudMonem's avatar

@siangboon and @jlrdw .. Hello guys thank you so much for the head up .. actually I dove into the php manual and it's soo interesting .. so many things to learn :D so thanks..

{{(ceil(($product->price_before - $product->price_after)/$product->price_before*100))}}

Now I did that in the blade view and it gave me the expected result I'm looking for .. actually this percentage thing is jut serving informing purpose .. nothing more.

I really think there is a better way I can get this into the controller and just call something like "$discount" in the blade view .. @siangboon can you please give me more input on how can I improve this by moving it to a dedicated class .. or even in the Product Model :)

siangboon's avatar

if you think it is related to your model, then just create a function and put your calculation works in that model and return the result.. so next time you can simply call $product->discount() but if you think this is applicable to multiple models then you can consider use trait or global helper function... ,

1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Add an accessor to the Product model

public function getDiscountAttribute() 
{
     return ceil(($this->price_before - $this->price_after)/$this->price_before *100))
}

//usage 
{{$product->discount}}
3 likes

Please or to participate in this conversation.