I want to add multi-column sorting feature in my data table made with laravel and livewire. I will receive an array of column names and sort direction from frontend and i have to order the query based on the received array.
Array example:
$sortColumns = [
'status' => 'asc',
'company' => 'asc',
'salary_group' => 'desc',
'name' => 'asc',
................
................
];
How do i perform the query on my model to chain these sorting of columns?
*** Edit: Also I want to paginate the query.
I have tried to chain orderBy on my query but the number of sorting columns in the array is not fixed. So I don’t know how to chain indefinite number of orderBy.
2
Answers
You could simply iterate over your Array and call
->orderBy()
:You may also leverage laravel collection methods for immutability: