⌘K
Noting Found

View all related articles

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:

    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.

    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

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

    We care about the protection of your data. Read our Privacy Policy.