In this blog post, we will take a look at how to use the Laravel orderBy clause in the Eloquent ORM.Laravel provides an expressive, fluent interface for creating and retrieving records in your database.
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.
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 1 – Laravel single column orderBy
So in this example i will use laravel query builder or eloquent single 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");
$Article = Article::orderBy('title', 'asc')->get();
}
}
Output will be if sortBy
is title :
select * from `articles` where order by title asc
Example 2 – 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 ?