LaravelLivewireTable - Sorting by role name
Hi all 👋 I'm having a little trouble with this package: https://github.com/rappasoft/laravel-livewire-tables
I tried to ask my question directly on Discord support but I didn't really get any feedback and I thought that here I might have a bit more luck. I don't know whether the problem is linked to the package or to the Query Builder.
Let me explain: I have a user table where I'm trying to sort by Role name (spatie permission). The standard display works fine but I can't set up the sorting, I get this error:
Rappasoft\LaravelLivewireTables\DataTableComponent::setBuilder(): Argument #1 ($builder) must be of type Illuminate\Database\Eloquent\Builder, null given, called in D:\laragon\www\...\...\vendor\rappasoft\laravel-livewire-tables\src\Traits\WithSorting.php on line 95
public function builder(): Builder
{
return User::query()
->where('active', 1);
}
And my Column :
Column::make(__('dashboard.users.role'))
->label(function ($row, Column $column) {
return view('tables.components.dashboard-users-roles')->withRow($row);
})
->sortable(function (Builder $query, $direction) {
$query->join('model_has_roles', 'users.id', '=','model_has_roles.model_id')
->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
->orderBy('roles.name', $direction);
}),
I can't see the problem, but here's the SQL query generated, which looks pretty good to me:
"select `users`.`id` as `id`, `users`.`username` as `username`, `users`.`name` as `name`, `users`.`firstname` as `firstname`, `users`.`email` as `email`, `users`.`created_at` as `created_at` from `users` inner join `model_has_roles` on `users`.`id` = `model_has_roles`.`model_id` inner join `roles` on `model_has_roles`.`role_id` = `roles`.`id` where `active` = ? order by `roles`.`name` asc
If I execute the query in my SQL software (HeidiSQL), I have the right sorting result (look at the screen). The firsts users have the role "admin", so it's correct.
I also tried to make the joins in the direct builder method :
public function builder(): Builder
{
return User::query()
->where('active', 1)
->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
->join('roles', 'model_has_roles.role_id', '=', 'roles.id');
}
And adapt the sorting method for the roles column :
Column::make(__('dashboard.users.role'))
->label(
function ($row, Column $column) {
return view('tables.components.dashboard-users-roles')->withRow($row);
}
)
->sortable(function (Builder $query, $direction) {
$query->orderBy('roles.name', $direction);
}),
On the loading, everything is fine. But when I click to the role column name, I have the same error 😓
If I DD the query on sortable function, I see It's the same that I execute on HeidiSQL so why WithSorting return null instead the Builder object? Is there another way? Thanks in advance 😃
Please or to participate in this conversation.