Replies: 6 comments 2 replies
-
why not using EDIT: let me elaborate class Product
{
public function getTotalAttribute()
{
return $this->cost + $this->total;
}
} if you want to add to every class Product
{
protected $appends = [ 'total' ];
// .... the rest
} |
Beta Was this translation helpful? Give feedback.
-
Thank you, I am aware of the The example I posted is a simple one but there certainly are more complicated calculations one may need to use for |
Beta Was this translation helpful? Give feedback.
-
@scibuff In a scope you can do this: function scopeWithTotal($query) {
if (is_null($query->getQuery()->columns)) {
$query->select($this->qualifyColumn('*'));
}
$query->addSelect(DB::raw('cost + shipping AS total'));
} Then: static::addGlobalScope('total', function(Builder $builder) {
$builder->withTotal();
} Or you can just be explicit about calling |
Beta Was this translation helpful? Give feedback.
-
I agree this is (years later) still weird behaviour. Even if it is a breaking change, it should be fixed. The
framework/src/Illuminate/Database/Query/Builder.php Lines 417 to 421 in 5a7f2b4
|
Beta Was this translation helpful? Give feedback.
-
Some further notes, as I was looking to add a scope which adds a column ad-hoc, that relies on a sub query. It seems the issue is arisen from the Added that DB::raw(...) is not regarded as querable.framework/src/Illuminate/Database/Query/Builder.php Lines 3995 to 4001 in 5050195 |
Beta Was this translation helpful? Give feedback.
-
Still a thing in 2025, here is how I personally tackled this: public function scopeWithIsLiked(Builder $query): Builder
{
$subQuery = /* Useless for the example */;
// Avoid to override current query columns select
$selects = $query->getSelect() ?? ['*'];
array_push($selects, DB::raw("exists($subQuery) as is_liked"));
return $query->select($selects);
} |
Beta Was this translation helpful? Give feedback.
-
Description:
When I try to add a custom column to my queries with
addSelect
orselectRaw
only the specified column is returned if$builder->columns
isnull
Steps To Reproduce:
Exptected:
Looking at the
Builder->addSelect
I see I need to do$builder->select( $builder->from.'.*' );
in myaddGlobalScope
closure, but this should be either specified in the docs (currently it says to useaddSelect
)or the
addSelect
should do it for non 'queryable` columns as wellBeta Was this translation helpful? Give feedback.
All reactions