Laravel 10 Usage of latest() for Eloquent Queries

Hello Artisan, today I'll show you the usage of latest() eloquent method in our Laravel application. So, let's get dive into our topic.

Table of Contents

  1. Example 1: Use for created_at column
  2. Example 2: Use for Other columns

Example 1: Use for created_at column

By default, Laravel uses created_at column for latest() method. So, if we see the below query.

User::latest()->paginate(15);

It means it'll sort our result in descending order by created_at column and after descending it'll paginate by 15 records.

Example 2: Use for Other Columns

So, as we see the example in step1, with the default column created_at in latest() method. And most of the devs doesn't even know that we can use any timestamps column as an argument in latest() method. So, let's see the below query first.

User::latest('date')->paginate(15);

So, this query will sort our result in descending order by the "date" column. So, we can see that by latest() method we can sort our result by passing any timestamp field as an argument.

That's it for today. I hope this short tips will be helpful in upcoming project. Thanks for reading. ๐Ÿ™‚