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.
Retrieving the last record is essential for scenarios like:
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.
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.
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
.
latest()
with EloquentThe 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'
]
orderBy()
with EloquentThe 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]'
]
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
.
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]'
]
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()
).
php artisan make:controller UserController
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);
}
}
routes/api.php
):
use App\Http\Controllers\UserController;
Route::get('/last-user', [UserController::class, 'getLastUser']);
http://localhost:8000/api/last-user
{
"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.
id
, created_at
) are indexed in the database for performance.latest()
, orderBy()
) for readability and model relationships.if ($lastUser)
).take(1)
or limit(1)
to minimize query overhead.latest()
, take(1)
): Efficient for timestamp-based queries, leveraging created_at
indexes.orderBy()
): Flexible but ensure the column is indexed to avoid slow queries.last()
): Simple but less flexible; avoid for complex sorting.For large tables, test query performance using Laravel’s DB::enableQueryLog()
to log execution times.
php artisan tinker
and check: User::count()
.created_at
vs. id
) matches your intent.CREATE INDEX idx_created_at ON users(created_at);
).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!
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: