Help Needed with Sorting an Accessor in Filament Table

I'm working on a Filament table where I need to display and sort by a computed accessor, formatted_ending_balance, in my Account model. The accessor calculates the ending balance based on account transactions and formats it. Account model:
class Account extends Model
{
public function formattedEndingBalance(): Attribute
{
return Attribute::get(function () {
return $this->ending_balance->convert()->formatWithCode();
});
}

protected function endingBalance(): Attribute
{
return Attribute::get(function () {
$company = $this->company;
$fiscalYearStart = $company->locale->fiscalYearStartDate();
$fiscalYearEnd = $company->locale->fiscalYearEndDate();

return Accounting::getEndingBalance($this, $fiscalYearStart, $fiscalYearEnd);
});
}
// Unrelated code...
class Account extends Model
{
public function formattedEndingBalance(): Attribute
{
return Attribute::get(function () {
return $this->ending_balance->convert()->formatWithCode();
});
}

protected function endingBalance(): Attribute
{
return Attribute::get(function () {
$company = $this->company;
$fiscalYearStart = $company->locale->fiscalYearStartDate();
$fiscalYearEnd = $company->locale->fiscalYearEndDate();

return Accounting::getEndingBalance($this, $fiscalYearStart, $fiscalYearEnd);
});
}
// Unrelated code...
Filament table column:
Tables\Columns\TextColumn::make('account.formatted_ending_balance')
->localizeLabel('Current Balance')
->alignment(Alignment::End)
->sortable(),
Tables\Columns\TextColumn::make('account.formatted_ending_balance')
->localizeLabel('Current Balance')
->alignment(Alignment::End)
->sortable(),
The problem is that when I try to sort by formatted_ending_balance, I get a SQL error because this accessor is not a database column. How can I enable sorting for this computed accessor in the Filament table? Is it currently possible? Any possible workarounds or similar solutions? Making it a database column is not an option for me based on my app logic. Thanks.
Solution:
You can’t. Sorting is done on DB level. If a db column is not an option you can sort.
Jump to solution
4 Replies
Solution
Dennis Koch
Dennis Koch6mo ago
You can’t. Sorting is done on DB level. If a db column is not an option you can sort.
Dennis Koch
Dennis Koch6mo ago
You could try overwriting the method that gets the actual results. Retrieve all the Results and sort them via PHP. Haven’t done that yet though. And it requires you to load all db entries every time.
Andrew Wallo
Andrew WalloOP6mo ago
Okay thank you for your help and suggestions. I suppose I just won't make it a sortable. Probably the best choice in this case
Dennis Koch
Dennis Koch6mo ago
Why can’t you add a db column though?
Want results from more Discord servers?
Add your server