How to Use Order By for Multiple Columns in Laravel 4?

PhpLaravelLaravel 4EloquentLaravel Query-Builder

Php Problem Overview


I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:

SELECT *
FROM mytable
ORDER BY
  coloumn1 DESC, coloumn2 ASC

How can I do this?

Php Solutions


Solution 1 - Php

Simply invoke orderBy() as many times as you need it. For instance:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

Produces the following query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

Solution 2 - Php

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

Solution 3 - Php

Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:

public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
    $result = $this->model->with($with);
    $dataSet = $result->where($where)
        // Conditionally use $orderBy if not empty
        ->when(!empty($orderBy), function ($query) use ($orderBy) {
            // Break $orderBy into pairs
            $pairs = array_chunk($orderBy, 2);
            // Iterate over the pairs
            foreach ($pairs as $pair) {
                // Use the 'splat' to turn the pair into two arguments
                $query->orderBy(...$pair);
            }
        })
        ->paginate($limit)
        ->appends(Input::except('page'));

    return $dataSet;
}

Now, you can make your call like this:

$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);

Solution 4 - Php

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
	->orderBy('email', 'DESC')
    ...
	->get();

Solution 5 - Php

$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSophyView Question on Stackoverflow
Solution 1 - PhprmobisView Answer on Stackoverflow
Solution 2 - PhpSagar NaliyaparaView Answer on Stackoverflow
Solution 3 - PhpmpemburnView Answer on Stackoverflow
Solution 4 - PhpHedayatullah SarwaryView Answer on Stackoverflow
Solution 5 - PhpHarshan MorawakaView Answer on Stackoverflow