I have table of dogs in my DB and I want to retrieve N latest added dogs
.
Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
Thank you very much for any help :)
You may try something like this: $dogs = Dogs::orderBy('id', 'desc')->take(5)->get(); Use orderBy with Descending order and take the first n numbers of records.
After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.
Laravel Get Last Month records Use the below laravel eloquent query to get the last month records from the database table. User::whereMonth('created_at', '=', Carbon::now()->subMonth()->month)->get(['name','created_at']); This query uses laravel method whereMonth() and get().
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy
with Descending
order and take the first n
numbers of records.
Update (Since the latest
method has been added):
$dogs = Dogs::latest()->take(5)->get();
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With