Introduction
There are various ways to do things in Laravel including fetching data from the database. Today we are going to see how to get the first and the last record from the database in case you need to do something with them, such as first register user or the last one ...etc.
Requisite
Basic Understanding on Laravel framework
Fetch First Record Using DB Facade
Let's take an example on users
table. So, all what you need to do in order to fetch the last record using DB
Facade is the following:
1DB::table('users')->orderBy('id', 'desc')->first();
Or
1DB::table('users')->latest->first();
Fetch First Record Using Eloquent
With the same procedure, we can work with eloquent models
1App\Models\User::orderBy('id', 'desc')->first();
Or
1App\Models\User::latest()->first();
Fetch Last Record Using DB Facade
Now, it's the time to fetch the first record from the database using the DB
facade
1DB::table('users')->first();
Fetch Last Record Using Eloquent
The same process in the DB
facade you can do it here
1App\Models\User::first();
Conclusion
Today we knew how to fetch first and last record from the database using DB
Facade and Eloquent
. So, You have the two methods and what fits your need to use it
Since there are no big deals in the performance in this situation between the two methods.
Hope this quick article helps you and if you find something useful don't forget to follow me on Twitter for latest tips and tricks about Laravel and the web development on general.