DEV Community

Khandokar Nafis Jaman
Khandokar Nafis Jaman

Posted on

latest() vs oldest() vs orderBy() in Laravel

To fetch sort data, we use latest, oldest and orderBy methods in laravel. The difference of these methods is: latest and oldest methods sort data according to the created_at column whereas orderBy methods sort data by the lexically.

Suppose, you have a table called post and you want to use latest methods, the syntax will be:

$posts = DB::table('posts')->latest()->get();
Enter fullscreen mode Exit fullscreen mode

It will sort data based on created_at column. And the syntax of the oldest methods is:

$posts = DB::table('posts')->oldest()->get();
Enter fullscreen mode Exit fullscreen mode

You can pass a column as a parameter. Let's say, I want, the data will be sorted based on title column. So, the syntax will be:

$posts = DB::table('posts')->latest('title')->get();
\\or
$posts = DB::table('posts')->oldest('title')->get();
Enter fullscreen mode Exit fullscreen mode

On the contrary, orderBy sort data lexically.

$posts = DB::table('posts')->orderBy('title')->get(); \\ascending
\\or
$posts = DB::table('posts')->orderBy('title', 'desc')->get(); \\ descending
Enter fullscreen mode Exit fullscreen mode

Thanks. happy coding!

Top comments (0)