Laravel order by latest, oldest and newest

269
laravel order by latest oldest newest

In this short article, we will learn about the meaning and usage of latest, oldest and newest methods in laravel. The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the table’s created_at column. Or, we may pass the column name that we wish to sort by.

The latest method sorts the records according to the created_at in descending order. Thus, we get the latest records first and the oldest record at last. A basic usage example is shown below:

Model::latest()->get()

This will return all the users’ record orders by created_at in descending. For testing, we can create a new route to list all users and hit the route to get the records.

<?php

use App\Models\User;
..........................

Route::get('users', function () {
    return User::latest()->get();
});

On the other hand, oldest method serves the opposite purpose. This method sorts the order of the records by created_at in ascending. Its usage is the same as the previous one.

Model::oldest()->get();

To give an example, we can create a route that returns records.

<?php

use App\Models\User;
..........................

Route::get('users', function () {
    return User::latest()->get();
});

There is also another method to sorts the records according to the given column name. For example, we can also sort the records in descending order according to the updated_at column (or any other column). Please note that the column should be of type datetime.

Model::newest('updated_at')->get();

Below is an example of its implementation.

<?php

use App\Models\User;
..........................

Route::get('users', function () {
    return User::newest('expire_at')->get();
});

That is all about sorting in Laravel. Don’t forget to comment your thoughts below.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.