50

What is the function of latest() in laravel?

Example:

public function activity()
{
    return $this->hasMany('App\Activity')
        ->with(['user', 'subject'])
        ->latest();
}

From Build an activity feed in Laravel on line 44.

I've been looking in the laravel documentation, but I couldn't find it...

boroboris
  • 1,548
  • 1
  • 19
  • 32
user3253002
  • 1,521
  • 3
  • 21
  • 43

4 Answers4

120

latest() is a function defined in Illuminate\Database\Query\Builder Class. It's job is very simple. This is how it is defined.

public function latest($column = 'created_at')
{
    return $this->orderBy($column, 'desc');
} 

So, It will just orderBy with the column you provide in descending order with the default column will be created_at.

nextt1
  • 3,858
  • 2
  • 18
  • 26
  • Can we pass array to the latest() method? – Tahir Afridi Jun 14 '19 at 13:40
  • 2
    @TahirAfridi, as mentioned in the documentation, "By default, the result will be ordered by the created_at column. Or, you may pass the column name that you wish to sort by" – Saeed Dec 23 '19 at 05:59
  • 1
    In short: It will by default get the NEWEST database entry according to the created_at column. – Sliq Apr 01 '20 at 14:56
  • not intuitive at all, I thought latest() would be the opposite of first(). – shamaseen Dec 01 '21 at 21:19
  • 2
    You can use `oldest()` as the opposite to `latest()` also. – Grant Oct 24 '22 at 15:56
  • It's strange – I have a query that needs to fetch millions of records, but when I try to get the latest one using orderBy('created_at', 'desc'), it seems to break the application. However, when I use the latest method instead, the query runs without any issues. – LipeTuga Mar 15 '23 at 06:23
8

->latest() fetches the most recent set of data from the Database. In short, it sorts the data fetched, using the 'created_at' column to chronologically order the data.

Joseph N
  • 189
  • 2
  • 7
  • 4
    Does it really fetch? – mirnis Sep 03 '20 at 21:06
  • 1
    Yes, It fetches and returns an array of records by their most recent – Joseph N Oct 25 '20 at 19:43
  • 2
    It doesn't fetch anything, it returns a query builder with the ordering chained to it. You would still need to call something like ->get(), ->first() etc. on to fetch any rows from the database – Alpaus Mar 17 '22 at 23:43
7

Add ->get() on your code like this:

public function activity()
{
    return $this->hasMany('App\Activity')
        ->with(['user', 'subject'])
        ->latest()->get();
}
francisco
  • 1,387
  • 2
  • 12
  • 23
Berthold Feujo
  • 338
  • 5
  • 12
0

latest() function in Laravel used to get latest records from database using default column created_at.

latest()is the equivalent to orderBy('created_at', 'desc')

Billu
  • 2,733
  • 26
  • 47