2 ways to fetch the first and last records from the database in laravel

Laravel 1 min read

Table of Content

    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:

    DB::table('users')->orderBy('id', 'desc')->first();
    

    Or

    DB::table('users')->latest->first();
    

    Fetch First Record Using Eloquent

    With the same procedure, we can work with eloquent models

    App\Models\User::orderBy('id', 'desc')->first();
    

    Or

    App\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

    DB::table('users')->first();
    

    Fetch Last Record Using Eloquent

    The same process in the DB facade you can do it here

    App\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.


    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    Our news letter sent once a week, every tuesday.