FilamentF
Filament3y ago
qcol

summarize and custom model attribute

Hi

I have a model attribute:

protected function sumRetail(): Attribute { return Attribute::make( get: fn () => $this->price_retail * $this->qty ); }

And I would like to summarize the sum_retail column.

With this notation, summarize does not work, but row summation works:

TablesColumnsTextColumn::make('sum_retail')->label('Value.')->alignRight() ->summarize(Sum::make()->numeric(decimalPlaces: 2)),

With this notation, summarize works, but row summation does not work.

TablesColumnsTextColumn::make('price_retail * qty')->label('Value')->alignRight() ->summarize(Sum::make()->numeric(decimalPlaces: 2)),

So how should this be correct?
Solution
<?php

namespace App\Tables\Components\Columns\Summarizers;

use Exception;
use Filament\Tables\Columns\Summarizers\Summarizer;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Schema;

class SumAttribute extends Summarizer
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->numeric();
    }

    /**
     * @return int | float | array<string, array<string, int>> | null
     */
    public function summarize(Builder $query, string $attribute): int | float | array | null
    {
        $column = $this->getColumn();
        $isField = Schema::hasColumn($this->getQuery()->getModel(), $column->getName());

        if ($isField) {
            throw new Exception("The [{$column->getName()}] column must be an Attribute.");
        }
        
        $limit = $this->getQuery()->getQuery()->limit;
        $offset = $this->getQuery()->getQuery()->offset;
        return $this->getQuery()->getModel()->get()->skip($offset)->take($limit)->pluck($attribute)->sum();
    }
}
Was this page helpful?