I think you have to use having on computed columns?
https://laravel.com/docs/10.x/queries#havingraw-orhavingraw
A link to a solution when not using mysql;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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:
estimated_value column?estimated_value column is available in the query and works correctly for filtering?Any advice or recommendations would be greatly appreciated!
Please or to participate in this conversation.