Skip to main content
PHP Blog

Back to all posts

How to Get the Last Record In A Laravel Query?

Published on
6 min read
How to Get the Last Record In A Laravel Query? image

Best Database Query Tools to Buy in October 2025

1 Database Systems: Design, Implementation, & Management

Database Systems: Design, Implementation, & Management

BUY & SAVE
$155.60 $259.95
Save 40%
Database Systems: Design, Implementation, & Management
2 Database Systems: Design, Implementation, & Management

Database Systems: Design, Implementation, & Management

BUY & SAVE
$86.49
Database Systems: Design, Implementation, & Management
3 Database Systems: Design, Implementation, & Management

Database Systems: Design, Implementation, & Management

BUY & SAVE
$86.49
Database Systems: Design, Implementation, & Management
4 Concepts of Database Management (MindTap Course List)

Concepts of Database Management (MindTap Course List)

BUY & SAVE
$54.86 $193.95
Save 72%
Concepts of Database Management (MindTap Course List)
5 Statistics: A Tool for Social Research and Data Analysis (MindTap Course List)

Statistics: A Tool for Social Research and Data Analysis (MindTap Course List)

BUY & SAVE
$118.60 $259.95
Save 54%
Statistics: A Tool for Social Research and Data Analysis (MindTap Course List)
6 Bioinformatics for Beginners: Genes, Genomes, Molecular Evolution, Databases and Analytical Tools

Bioinformatics for Beginners: Genes, Genomes, Molecular Evolution, Databases and Analytical Tools

BUY & SAVE
$44.96 $59.95
Save 25%
Bioinformatics for Beginners: Genes, Genomes, Molecular Evolution, Databases and Analytical Tools
7 Data Mining: Practical Machine Learning Tools and Techniques (Morgan Kaufmann Series in Data Management Systems)

Data Mining: Practical Machine Learning Tools and Techniques (Morgan Kaufmann Series in Data Management Systems)

  • EXCLUSIVE 'NEW' BADGE BOOSTS CUSTOMER TRUST AND INTEREST.
  • FRESH DESIGNS ATTRACT ATTENTION AND DRIVE IMPULSE BUYING.
  • LIMITED TIME OFFERS CREATE URGENCY FOR PURCHASING 'NEW' ITEMS.
BUY & SAVE
$54.94 $69.95
Save 21%
Data Mining: Practical Machine Learning Tools and Techniques (Morgan Kaufmann Series in Data Management Systems)
8 The Manga Guide to Databases (The Manga Guides)

The Manga Guide to Databases (The Manga Guides)

BUY & SAVE
$19.95 $24.99
Save 20%
The Manga Guide to Databases (The Manga Guides)
+
ONE MORE?

To get the last record in a Laravel query, you can use the latest() method and then the first() method on your query builder instance. Here's an example:

$latestRecord = YourModel::latest()->first();

In this example, YourModel represents the model class for the table you want to query.

The latest() method orders the records in descending order based on the model's default timestamp column (usually created_at) or any other specified column. It essentially sorts the records in reverse chronological order.

Then, the first() method is applied to get the first record from the sorted query result, which would be the most recent record.

By combining these two methods, you can retrieve the last (most recent) record from a Laravel query.

How do you get the last record using Eloquent ORM in Laravel?

To get the last record using Eloquent ORM in Laravel, you can use the latest() method followed by the first() method. Here is an example:

$lastRecord = YourModel::latest()->first();

This will retrieve the last record from the database based on the primary key. The latest() method orders the records in descending order by the primary key, while the first() method retrieves the first record.

Can you use a subquery to retrieve the last record in Laravel?

Yes, you can use a subquery to retrieve the last record in Laravel. Here's an example of how you can do it:

$lastRecord = DB::table('your_table') ->where('id', '=', function ($query) { $query->select(DB::raw('MAX(id)')) ->from('your_table'); }) ->first();

dd($lastRecord);

In this example, we are using the DB facade to build the query. The subquery is used in the where clause to get the maximum id from the same table. The first method is used to retrieve the first (in this case, the last) record matching the criteria.

You can replace 'your_table' with the actual table name you are working with.

What is the result type when retrieving the last record in Laravel?

The result type when retrieving the last record in Laravel is an instance of the model class representing the database table.

Can you retrieve the last record from a relationship in Laravel?

Yes, Laravel provides several methods to retrieve the last record from a relationship.

One way is by using the latest() method combined with the first() or get() method. For example, if you have a users table with a posts relationship, you can retrieve the latest post for a specific user using the following code:

$user = User::find($id); $latestPost = $user->posts()->latest()->first();

Alternatively, you can use the orderByDesc() method to sort the relationship records in descending order of a specific column and then retrieve the first record:

$user = User::find($id); $latestPost = $user->posts()->orderByDesc('created_at')->first();

You can also use the first() method directly on the relationship without any sorting methods. This will retrieve the first related record, assuming it's sorted by the primary key:

$user = User::find($id); $latestPost = $user->posts()->first();

These techniques can be applied to retrieve the last record from any type of relationship in Laravel, such as one-to-many, many-to-many, or polymorphic relationships.

What are the different types of queries in Laravel?

In Laravel, there are several types of queries that can be performed using the Eloquent ORM:

  1. Basic Queries: These are simple queries that retrieve data from a single table. For example: DB::table('users')->get(): Retrieves all records from the "users" table. DB::table('users')->where('name', 'John')->first(): Retrieves the first record from the "users" table where the name is "John".
  2. Select Statement: This is used to retrieve specific columns from a table. For example: DB::table('users')->select('name', 'email')->get(): Retrieves only the "name" and "email" columns from the "users" table.
  3. Joins: These are used to combine rows from multiple tables based on a related column. For example: DB::table('users')->join('orders', 'users.id', '=', 'orders.user_id')->select('users.*', 'orders.order_date')->get(): Retrieves all users along with their corresponding orders.
  4. Aggregates: These are used to perform calculations on a set of values. Examples include count, sum, max, min, etc. For example: DB::table('users')->count(): Retrieves the count of all records in the "users" table.
  5. Conditional Queries: These are used to add conditions to the query, such as filtering, sorting, or limiting results. For example: DB::table('users')->where('age', '>', 18)->orderBy('name')->skip(10)->take(5)->get(): Retrieves users where the age is greater than 18, ordered by name, skipping the first 10 records, and retrieving the next 5.
  6. Insert and Update Queries: These are used to add or modify data in a table. For example: DB::table('users')->insert(['name' => 'John', 'email' => 'john@example.com']): Inserts a new record into the "users" table. DB::table('users')->where('id', 1)->update(['name' => 'Jane']): Updates the name of the user with ID 1 in the "users" table.
  7. Delete Queries: These are used to remove data from a table. For example: DB::table('users')->where('id', 1)->delete(): Deletes the user with ID 1 from the "users" table.

How do you limit the number of records retrieved in a Laravel query?

In Laravel, you can limit the number of records retrieved from a database using the take() method. Here's an example of how to limit the number of records retrieved in a Laravel query:

$users = DB::table('users')->take(5)->get();

In the above example, we are retrieving records from the "users" table but limiting the query to retrieve only 5 records. The take() method specifies the number of records to retrieve.

You can also chain the take() method with other query builder methods like select(), where(), etc. For example:

$users = DB::table('users') ->select('name', 'email') ->where('active', true) ->take(10) ->get();

In this example, we are retrieving the names and emails of active users, and limiting the query to retrieve only the first 10 records.

Note that the take() method retrieves the records in the order they were inserted into the database. If you want to retrieve the records in a specific order, you can use the orderBy() method along with the take() method.

Can you retrieve the last record in a query without sorting the results?

No, you cannot retrieve the last record in a query without sorting the results. The order in which the records are returned by a query is not guaranteed unless you specify an ORDER BY clause to sort the results based on a particular column. Without sorting, the database engine determines the most efficient way to retrieve the records, which may result in different orders on different executions.