laravel-livewire-tables icon indicating copy to clipboard operation
laravel-livewire-tables copied to clipboard

[Bug]: sortable() doesn't work when i use label

Open bhagat-abhishek opened this issue 5 months ago • 4 comments

What happened?

I am trying to make use of the label method for showing the views from a relation, but eventually it doesn't work. I tried to look for a solutions but even after months i am unable to fix, can anyone help me reslove this issue.

Here is the code from the component table

Column::make('Views')->label(fn ($row, Column $column) => $row->visit()->count())->sortable(),
Column::make('Whatsapp')->label(fn ($row, Column $column) => Click::where('listing_id', $row->id)->where('is_whatsapp', true)->count())->sortable(),
Column::make('Call')->label(fn ($row, Column $column) => Click::where('listing_id', $row->id)->where('is_call', true)->count())->sortable(),

How to reproduce the bug

When using the label(), with sortable() itsnt working; also when I tried one solution from the closed issue #1033 but it didn't work when i tried.

Package Version

2.11

PHP Version

8.1.x

Laravel Version

10.0

Alpine Version

No response

Theme

None

Notes

No response

Error Message

No response

bhagat-abhishek avatar Jan 12 '24 18:01 bhagat-abhishek

@rappasoft @WhereIsLucas @dmyers @kijtra can anyone please help me

bhagat-abhishek avatar Jan 24 '24 18:01 bhagat-abhishek

@bhagat-abhishek - Apologies for the delay!

So sortable() when using a label Column requires a callback to be used. This is because it's not a "real field", so the package won't try to do anything with it in terms of the database query, as it doesn't know how to map it back to the database.

e.g.

Column::make('Address')
  ->label(fn ($row, Column $column) => $row->addr_line1)->sortable(
        fn(Builder $query, string $direction) => $query->orderBy('addr_line_2', $direction)
    ),

Worth noting, looking at your code, that you should really be using relationships to pull that data into the main builder(), so that you aren't executing multiple queries per row.

lrljoe avatar Feb 01 '24 04:02 lrljoe

@lrljoe thank you, let me try that.

bhagat-abhishek avatar Feb 01 '24 05:02 bhagat-abhishek

Definitely look at relationships for those models instead of running separate queries though! It'll run much better

lrljoe avatar Feb 01 '24 05:02 lrljoe