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

nabilunfarhanun's avatar

How to run query with model function?

So, I have a model for products of a website. In the model I use a function to calculate the price of the product. It is something like this,

class Product extends Model
{

    public function price()
    {
        // logic to calculate price
        // this logic may depend on many things and may change in future.
        return $price
    }
}

I can view this successfully in my blade view by using following.

{{ $product->price() }}

However, I want to use it to do some query. There may be other filtering. Those are working fine. But whenever I want to use the return value of price function in the query it is giving an error.

$products = Product::query();
//There may be some other filtering query
$products = $products->where('price()','<',request('maxPrice'));
//Maybe some more filtering query
$products = $products->get();
return view('product',compact('products'));

My question is how can I run query with the price function of my model. Also, if you can think of an alternative way to achieve this then please teach me.

0 likes
1 reply
mabdullahsari's avatar

Your way of thinking is wrong. You cannot use app logic inside of your query. That piece of state should be already available in your database to be able to run queries against it or else you can't.

You need to fetch all of your products and use Collection methods to do the filtering as the price is calculated on the fly. Something like:

$products->reject(static function ($product) {
    return $product->price() > request('maxPrice');
});

A better approach would be to save this piece of information with your product in your database so you do not have to fetch them all every single time and can already carry out the filtering via the database query. If it is repetitive logic, you can for example use model observers to calculate that field just before persisting it to the database.

Please or to participate in this conversation.