Get Last Record in Laravel 12 – 5 Methods Explained

Hey there, Laravel enthusiasts! I’m thrilled to dive into one of the most common tasks in Laravel development: retrieving the last record from a database table. Whether you’re building a blog, an e-commerce platform, or an API, knowing how to fetch the latest record efficiently is a must.

In this guide, I’ll walk you through five practical methods to get the last record in Laravel 12 using Query Builder and Eloquent ORM. With clear code snippets and tips, you’ll master this task in no time.

Why Fetching the Last Record Matters

Retrieving the last record is essential for scenarios like:

  1. Displaying the latest user registration.
  2. Showing the most recent order in an e-commerce app.
  3. Fetching the latest post in a blog or forum.
  4. Auditing the most recent activity in a system.

Laravel 12 offers powerful tools like Eloquent ORM and Query Builder, making this task flexible and efficient. Let’s explore five methods to achieve this, each with its use case and benefits.

Step-by-Step Guide: 5 Methods to Get the Last Record in Laravel 12

Get Last Record in Laravel 12 – 5 Methods Explained

Below, I’ll explain five methods to retrieve the last record from a database table (e.g., users table) in Laravel 12. Each method includes a code snippet, explanation, and when to use it. Ensure your Laravel 12 project is set up, and your database is configured in the .env file.

Prerequisites

Laravel 12 installed (composer create-project --prefer-dist laravel/laravel last-record-example).

Database configured (e.g., MySQL, PostgreSQL) in env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

users table migrated (php artisan migrate).

Let’s assume you have a User model (app/Models/User.php) and a users table with columns: id, name, email, created_at.

Method 1: Using latest() with Eloquent

The latest() method retrieves the most recent record based on the created_at timestamp (or another column).

use App\Models\User;

$lastUser = User::latest()->first();

Explanation:

- latest() orders records by created_at in descending order (newest first).

- first() fetches the top record.

- You can specify a custom column: latest('updated_at').

When to Use:

- Ideal for simple queries when created_at or updated_at determines the latest record.

- Perfect for blogs, user registrations, or activity logs.

Output:

// Example: Returns the latest user
[
    'id' => 10,
    'name' => 'John Doe',
    'email' => '[email protected]',
    'created_at' => '2025-05-01 10:00:00'
]

 

Method 2: Using orderBy() with Eloquent

The orderBy() method offers flexibility to sort by any column.

use App\Models\User;

$lastUser = User::orderBy('id', 'desc')->first();

Explanation:

orderBy('id', 'desc') sorts the users table by id in descending order.

first() retrieves the first record (highest id).

- Replace 'id' with any column (e.g., 'email', 'created_at').

When to Use:

- Use when sorting by a custom column (e.g., id, order_date) instead of timestamps.

- Suitable for scenarios like fetching the latest order by order_id.

Output:
Similar to Method 1, returns the record with the highest id.

 

Method 3: Using last() with Query Builder

The last() method in Query Builder fetches the last record based on the primary key.

use Illuminate\Support\Facades\DB;

$lastUser = DB::table('users')->last();

Explanation:

DB::table('users') targets the users table.

last() retrieves the record with the highest primary key (id).

- Note: last() may not work as expected with custom sorting; use orderBy() for flexibility.

When to Use:

- Use for raw Query Builder queries without Eloquent models.

- Good for quick scripts or when avoiding model overhead.

Output:

// Example: Returns the user with the highest id
(object) [
    'id' => 10,
    'name' => 'John Doe',
    'email' => '[email protected]'
]

 

Method 4: Using take(1) with latest()

The take(1) method limits the result to one record, combined with latest() for ordering.

use App\Models\User;

$lastUser = User::latest()->take(1)->get()->first();

Explanation:

latest() orders by created_at (descending).

take(1) limits to one record.

get()->first() retrieves the single record as a model instance.

- Alternative: User::latest()->limit(1)->get()->first().

When to Use:

- Use when you need to ensure only one record is returned, especially in complex queries.

- Useful for APIs returning a single latest item.

Output:
Same as Method 1, returns the latest record based on created_at.

 

Method 5: Using Raw SQL Query

For advanced users, a raw SQL query provides full control.

use Illuminate\Support\Facades\DB;

$lastUser = DB::select('SELECT * FROM users ORDER BY id DESC LIMIT 1')[0];

Explanation:

SELECT * FROM users ORDER BY id DESC LIMIT 1 fetches the record with the highest id.

DB::select() executes the raw query.

[0] accesses the first (and only) result as an object.

When to Use:

- Use for custom database queries or when Eloquent/Query Builder isn’t suitable.

- Ideal for legacy systems or complex sorting logic.

Output:

// Example: Returns the user with the highest id
(object) [
    'id' => 10,
    'name' => 'John Doe',
    'email' => '[email protected]'
]

 

Example: Real-World Application

Let’s tie these methods to a practical scenario. Suppose you’re building a Laravel 12 API to display the latest registered user on a dashboard. Here’s how to implement it using Method 1 (latest()).

  1. Create a Controller:
php artisan make:controller UserController
  1. Add Logic (app/Http/Controllers/UserController.php):
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function getLastUser()
    {
        $lastUser = User::latest()->first();
        if ($lastUser) {
            return response()->json([
                'name' => $lastUser->name,
                'email' => $lastUser->email,
                'registered_at' => $lastUser->created_at
            ], 200);
        }
        return response()->json(['message' => 'No users found'], 404);
    }
}
  1. Define Route (routes/api.php):
use App\Http\Controllers\UserController;

Route::get('/last-user', [UserController::class, 'getLastUser']);
  1. Test with Postman:
  • URL: http://localhost:8000/api/last-user
  • Method: GET
  • Response:
{
    "name": "John Doe",
    "email": "[email protected]",
    "registered_at": "2025-05-01 10:00:00"
}

This API endpoint uses Method 1 for simplicity but can be adapted to any method based on your needs.

Best Practices for Retrieving the Last Record

  1. Indexing: Ensure columns used for sorting (e.g., id, created_at) are indexed in the database for performance.
  2. Use Eloquent for Models: Prefer Eloquent (latest(), orderBy()) for readability and model relationships.
  3. Avoid Raw Queries: Use raw SQL only when necessary, as it bypasses Laravel’s security features.
  4. Handle Empty Results: Always check if a record exists to avoid null errors (e.g., if ($lastUser)).
  5. Optimize for Large Tables: For large datasets, use take(1) or limit(1) to minimize query overhead.
  6. Combine with Authentication: For secure APIs, protect routes with Laravel 12 authentication (e.g., Laravel Passport, as discussed in your previous article).

Performance Considerations

  1. Method 1 & 4 (latest(), take(1)): Efficient for timestamp-based queries, leveraging created_at indexes.
  2. Method 2 (orderBy()): Flexible but ensure the column is indexed to avoid slow queries.
  3. Method 3 (last()): Simple but less flexible; avoid for complex sorting.
  4. Method 5 (Raw SQL): Fast but requires manual optimization (e.g., indexes, query tuning).

For large tables, test query performance using Laravel’s DB::enableQueryLog() to log execution times.

Troubleshooting Common Issues

  1. No Records Returned: Ensure the table has data. Run php artisan tinker and check: User::count().
  2. Incorrect Sorting: Verify the column used for sorting (e.g., created_at vs. id) matches your intent.
  3. Performance Issues: Add indexes to frequently queried columns (e.g., CREATE INDEX idx_created_at ON users(created_at);).
  4. Composer Errors: If you encounter “‘composer’ is not recognized…”, ensure Composer is installed and added to your system’s PATH.

Conclusion

Fetching the last record in Laravel 12 is a breeze with the right tools. Whether you use latest(), orderBy(), or a raw SQL query, each method has its strengths depending on your project’s needs.

By following this guide, you’ve learned five practical ways to retrieve the latest record, complete with code snippets and best practices. Combine these techniques with Laravel 12’s powerful features like Eloquent and Query Builder to build efficient, scalable applications. Start implementing these methods today, and take your Laravel database queries to the next level!

Frequently Asked Questions (FAQs)

Q1: What’s the easiest way to get the last record in Laravel 12?
A: Use User::latest()->first() for a simple, timestamp-based query. It’s beginner-friendly and efficient.

Q2: Can I get the last record based on a custom column?
A: Yes, use User::orderBy('your_column', 'desc')->first() or User::latest('your_column')->first().

Q3: How do I handle empty tables when fetching the last record?
A: Check if the result exists: if ($record = User::latest()->first()) { return $record; } else { return null; }.

Q4: Is Query Builder faster than Eloquent for getting the last record?
A: Query Builder (DB::table('users')->last()) is slightly lighter but less flexible than Eloquent. Use Eloquent for model relationships.

Q5: How can I optimize queries for large tables in Laravel 12?
A: Index sorting columns (e.g., created_at), use take(1) or limit(1), and enable query logging to monitor performance.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS