Return the last record in a One to many Eloquent Relation using Laravel

Stefan Bogdanescu

Founder & Senior Architect · 2026-06-29

Laravel Company
# Return the Last Record in a One to Many Eloquent Relation Using Laravel As developers working with relational data in Laravel, we frequently encounter scenarios where we don't just need *all* related records, but specifically the *most recent*, *latest*, or *first* record. When dealing with a `One-to-Many` relationship, simply eager loading all associated items via `with()` will return every single job, which is often inefficient if you only require one specific item—in this case, the user's last job. The challenge lies in transforming a collection of related models into a single, desired model efficiently. Let’s dissect your attempt and explore the most robust ways to solve this problem using Eloquent. ## The Pitfall of Simple Eager Loading Your initial approach involved: ```php return User::with( $this->particulars() // I want the last record from this line )->orderBy('id', 'desc')->get(); ``` While ordering and retrieving the collection is a valid step, when using `with()`, Eloquent typically loads *all* related models into memory. Even if you order them descendingly, you are still loading potentially many job records for each user before filtering or selecting just one. This method is better suited for fetching all jobs rather than optimizing for a single "last" item per parent record. ## Solution 1: Using Subqueries and `with()` (The Collection Approach) A very readable way to achieve this, especially when you anticipate needing the relationship data alongside other user details, is to fetch the full set of related records first, sort them, and then manually select the desired one in your controller or resource. This approach relies heavily on database sorting capabilities. If we assume the `jobs` table has an auto-incrementing `id`, ordering by `id` descending will put the latest job at the top of the result set for each user group. **Example Implementation:** In your controller method, you would adjust the query structure: ```php public function index() { $users = User::with('jobs') ->with(['jobs' => function ($query) { // Subquery to select only the latest job per user $query->orderBy('id', 'desc') ->limit(1); }]) ->get(); return UserResource::collection($users); } ``` In this example, we use a nested `with()` structure. The outer `with('jobs')` loads all jobs, but the inner anonymous function modifies how the `jobs` relationship is loaded: it tells Eloquent to only fetch the single job where `id` is the maximum for that user group (or simply rely on the sorting mechanism if you structure the query slightly differently). A cleaner approach often involves using **dot notation** and ensuring the ordering is applied directly to the relationship being loaded, though complex aggregation often requires direct joins or subqueries. ## Solution 2: Optimizing with a Custom Scope or Advanced Joins (The Database Approach) For maximum performance, especially on large datasets, relying purely on Eloquent's eager loading for this specific task can be cumbersome. The most performant solution involves using a **subquery** or a **LEFT JOIN** to find the maximum ID first, and then fetching the corresponding record. This delegates the complex sorting logic directly to the database engine, which is significantly faster than pulling potentially thousands of rows into PHP memory only to discard them. Here is how you might structure the query using a subquery approach (conceptually): 1. **Find the Maximum Job ID per User:** Determine the latest `job_id` for every user. 2. **Join and Select:** Join the `users` table with the `jobs` table, filtering where the job's ID matches the maximum ID found in step 1. While this requires slightly more complex Eloquent structuring (often achieved via `whereHas` or raw queries), it guarantees that only one record is retrieved per user without loading unnecessary relational data. This principle of optimizing data retrieval through smart querying is fundamental to leveraging powerful tools like those provided by the Laravel ecosystem, which emphasizes clean and efficient data manipulation. ## Conclusion To return the last record in a one-to-many relationship efficiently, avoid simply eager loading everything and filtering in PHP. Instead, embrace database-level optimization. For most scenarios, structuring your query to find the maximum related ID first (using subqueries or `JOIN` operations) ensures that you are only fetching the minimal required data from the database. As you build complex applications on Laravel, mastering these performance-oriented querying techniques will make your codebase cleaner, faster, and more scalable. Always remember to explore the documentation and best practices provided by the Laravel community for advanced Eloquent features.