skip to Main Content

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


  1. You could simply iterate over your Array and call ->orderBy():

    $sortColumns = [
        'status' => 'asc',
        'company' => 'asc',
        'salary_group' => 'desc',
        'name' => 'asc',
        ................
        ................
    ];
    
    $query = Model::query();
    
    foreach ($sortColumns as $column => $order) {
      $query->orderBy($column, $order);
    }
    
    // Any other query logic
    
    $result = $query->get();
    
    Login or Signup to reply.
  2. You may also leverage laravel collection methods for immutability:

        $sortColumns = [
            'status' => 'asc',
            'company' => 'asc',
            'salary_group' => 'desc',
            'name' => 'asc',
        ];
    
       $query = collect($sortColumns)
           ->reduce(function ($query, $direction, $column) {
               return $query->orderBy($column, $direction);
           }, Model::query()
        );
    
       $results = $query->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search