понедельник, 11 марта 2024 г.

Adding a Custom Field in Laravel's Scope Without Impacting Other Selections

Somehow I didn’t immediately understand this, but somehow it’s quite simple, but not obvious from the start.  

If you need to add a field in a scope, but in such a way that it does not affect other selections or does not select only this field, you can do this:

 
public static function scopeAddCustom(Builder $query): Builder
{
    return $query->select($query->getQuery()->columns ?? '*')
        ->addSelect(new Expression('TRUE as custom'));
}