defaultSort() with an enum

Using defaultsort() on an enum column sorts as per the enum value...but the user would be expecting it to sort on the human readable value....

is there a way of overcoming this ?
Solution
Ok, here is a solution, feels a bit hacky, if anyone has a better one....feel free to tell.

In the enum, add a reverse label case method:

    public static function sortCaseSql(string $column) : string
    {
        $cases = collect(self::cases())
            ->map(fn (self $case) => "WHEN '{$case->value}' THEN '" . addslashes($case->getLabel()) . "'"
            )
            ->implode(' ');

        return "CASE $column $cases END";
    } 


In the resource, add a virtual column:

   public static function getEloquentQuery() : Builder
    {
        return parent::getEloquentQuery()
            ->select('*')
            ->selectRaw(enumKbGroup::sortCaseSql('kb_group') . ' as kb_group_label');
    }


In the table, just use the virtual column as you would anyway:

         TextColumn::make('kb_group_label')
                ->label('Category')
                ->badge()
                ->sortable(),


and same in the table method:

->defaultSort('kb_group_label', 'asc')
Was this page helpful?