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.
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.
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. ๐