rappasoft / laravel-livewire-tables

A dynamic table component for Laravel Livewire
https://rappasoft.com/docs/laravel-livewire-tables/v2/introduction
MIT License
1.7k stars 320 forks source link

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

Closed bhagat-abhishek closed 4 months ago

bhagat-abhishek commented 5 months ago

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 commented 5 months ago

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

lrljoe commented 5 months ago

@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.

bhagat-abhishek commented 5 months ago

@lrljoe thank you, let me try that.

lrljoe commented 5 months ago

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