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

MostofaL's avatar

How to Filter Eloquent Results Based on a Computed Column in Laravel?

I'm working on a Laravel project and need to calculate an estimated_value for each record in my SalesLead model by multiplying the probability and value columns. My goal is to filter records based on this calculated value.

To achieve this, I tried adding a computed column using a global scope:

class EstimatedValueScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $builder->addSelect([
            '*',
            \DB::raw('COALESCE(probability, 0) * COALESCE(value, 0) * 0.01 AS estimated_value'),
        ]);
    }
}

This scope is applied in my SalesLead model:

class SalesLead extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new EstimatedValueScope);
    }
}

I want to filter records by this computed estimated_value, like so:

$salesLeads = SalesLead::where('estimated_value', '>', 1000000)->get();

However, I'm encountering an SQL error:

SQLSTATE[42703]: Undefined column: 7 ERROR:  column "estimated_value" does not exist
LINE 1: ...t count(*) as aggregate from "sales_leads" where ("estimated...
                                                         ^

Note: It's important for me to use Eloquent's where method for filtering by estimated_value, instead of resorting to whereRaw.

Questions:

  1. How can I effectively filter and query using this computed estimated_value column?
  2. Is applying a global scope the best approach for this scenario? If not, what alternative would you suggest?
  3. How can I make sure that the estimated_value column is available in the query and works correctly for filtering?

Any advice or recommendations would be greatly appreciated!

0 likes
2 replies
vincent15000's avatar

If you have defined the custom computed estimated_value (appended property) inside the model in Laravel, then you can't filter using this property in the database because the column doesn't exist in the database.

1 like

Please or to participate in this conversation.