How can i the Get Last Record from Database in Laravel?

Spread the love

Hello Guys,

In this guide, you’ll discover how to get the Last Record from Database in a Laravel query. We’ll explore various methods for obtaining the most recent entry in a Laravel database. We’ll also provide a practical example of fetching the latest created record using Laravel.

There are multiple approaches to obtain the last record from a database table in your Laravel project, such as using the latest() or orderBy() methods. In the example below, you’ll see how to retrieve the very last record from the table.

Explore a straightforward illustration of fetching the latest record from a table in Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 projects.

Examples of Last Record from Database:

Also Read: How to rename Git Branch Name with Git Command?

Example 1: Get Last Record Using latest() & first()

I have an “Posts” table, and my objective is to retrieve the most recent entry from this table. In the initial example, I employ the combination of the latest() and first() methods. The latest() method is utilized to retrieve the most recently created record, and the first() method is used to obtain a single record:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $last = Post::latest()->first();
  
        dd($last);
    }
}

Example 2: Get Last Record Using orderBy() & first()

In this illustration, I utilized the orderBy() function associated with the “id” attribute. This method consistently retrieves the record with the highest “id.”

Also Read: How to integrate LINKEDIN LOGIN in Laravel 10

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $last = Post::orderBy('id', 'DESC')->first();
  
        dd($last);
    }
}

Example 3: Get Last Record Using latest(‘id’) & first()

In this illustrative example of latest() with an argument, latest() will automatically consider the “created_at” field as the default. However, if you prefer to specify a different field, you can provide the field name as an argument. This flexible approach allows you to customize your query to suit your specific needs.

Also Read: How to remove a column from a table in Laravel migration?

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $last = Post::latest('id')->first();
  
        dd($last);
    }
}

We trust you’ll discover our Laravel Blogs to be a valuable resource.

Leave a Comment