In this blog post, we will take a look at how to use the Laravel multiple orderBy clause in the Eloquent ORM. You can order query results by multiple columns using the orderBy method. This is useful when you want to sort by multiple criteria. In this post, we’ll show you how to use the orderBy method to sort query results by multiple columns
When we work with databases in Laravel, we often need to order the results we get back from the query. For example, we may want to get all the articles in alphabetical order, or we may want to get all the products in order of price. Laravel makes this easy to do with the orderBy
clause.
The orderBy
clause takes two parameters: the column to order by and the direction to order in. The direction can be either ‘asc’ for ascending or ‘desc’ for descending.
Laravel multiple orderBy example
Let’s take a look at Laravel orderBy clause in eloquent with example. Say we have a articles table with the following columns: id, title, email, created_at. We can use the following query to get all the articles in alphabetical order:
$articles = Article::orderBy('title', 'asc')->get();
This will give us an array of Articles objects, ordered by the title column in ascending order.
If we want to get the articles in reverse alphabetical order, we can change the direction to ‘desc’:
$articles = Article::orderBy('title', 'desc')->get();
Laravel orderby multiple columns
We can also order by multiple columns. For example, if we want to get the users in alphabetical order, but order by created_at in reverse order for those with the same name:
$articles = Article::orderBy('title', 'desc')->orderBy('created_at', 'desc')->get();
This can be useful if you want to show name alphabetically with recent articles.
Example – Laravel multiple column orderBy
So in this example i will use laravel query builder or eloquent multiple column orderBy .
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$sortBy=$request->get("sortBy");
$articles = Article::orderBy('title', 'desc')->orderBy('created_at', 'desc')->get();
}
}
Output will be if sortBy
is title :
select * from `articles` order by title DESC, created_at desc
Also Read : How to use conditional orderBy clause in Laravel 8 eloquent ?