title: Laravel API resources, get only the latest occurrence from a collection
body: <p>Hi I am developing an api in laravel for an online course system. In this scheme I have a standard table for users, a table for courses and a pivot table that relates courses and users according to which they sign up for each course.</p>
  <p>This last table also carries the events related to the progress of each user in the course, that is, Subscribed, Progress x%, Completed, Approved, so that each user can have multiple entries in the course_users table.</p>
  <p>So far everything is clear and everything is fine, the point is that at a certain moment I need to return a json object with the information of the courses and pointed users, this can be clearly achieved using resource collection in the following way:</p>
  <p><strong>CourseCollection.php</strong></p>
  <pre><code>&lt;?php
  
  namespace App\Http\Resources;
  
  use Illuminate\Http\Resources\Json\ResourceCollection;
  use App\Http\Resources\CargoResource;
  
  class CourseCollection extends ResourceCollection
  {
      /**
       * Transform the resource collection into an array.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return array
       */
      public function toArray($request)
      {
          return [
              'data' =&gt; CourseResource::collection($this-&gt;collection),
              'links' =&gt; [
                  'self' =&gt; 'link-value',
              ],
          ];
      }
  }
  </code></pre>
  <p><strong>CourseResource.php</strong></p>
  <pre><code>&lt;?php
  
  namespace App\Http\Resources;
  
  use Illuminate\Http\Resources\Json\JsonResource;
  
  class CourseResource extends JsonResource
  {
      /**
       * Transform the resource into an array.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return array
       */
      public function toArray($request)
      {
          return [
              'id' =&gt; $this-&gt;id,
              'title'=&gt; $this-&gt;title,
              'description'=&gt; $this-&gt;description,
              'price'=&gt; $this-&gt;price,
              'users' =&gt; CourseUserResource::collection($this-&gt;whenLoaded('users'))
          ];
      }
  }
  </code></pre>
  <p><strong>CourseUserResource.php</strong></p>
  <pre><code>&lt;?php
  
  namespace App\Http\Resources;
  
  use Illuminate\Http\Resources\Json\JsonResource;
  
  class CourseUserResource extends JsonResource
  {
  
      public function toArray($request)
      {
  
          return [
              'course_id'=&gt; $this-&gt; course_id,
              'user_id'=&gt; $this-&gt;user_id,
              'event'=&gt; $this-&gt;event,
              'event_date' =&gt; $this-&gt;created_at-&gt;format('Y-m-d')
          ];
      }
  }
  </code></pre>
  <p>The problem to be solved is that with this scheme I obtain a collection of events for each user and course, but what I am needing is only the last event of each user, to know what their status is in relation to the course.</p>
  <p>I am analyzing the option to perform the query by sql and then manually build the json object, but I would like to have a &quot;laravel style&quot; solution</p>
  <p>Any ideas will be welcome!</p>
  <p><a href="https://i.stack.imgur.com/cKNPp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cKNPp.png" alt="EER Diagram" /></a></p>
  <p><strong>Added Models &amp; Controllers for clarification</strong></p>
  <pre><code>class Course extends Model
  {
  
      protected $fillable = [
          'title',
          'slug',
          'description',
          'course_category_id',
          'price',
          'published'
      ];
  
  ...
  
      public function history()
      {
          return $this-&gt;belongsToMany(CourseUser::class, 'course_id', 'id')-&gt;latest();
      }
  
      public function scopePublished($query)
      {
          return $query-&gt;where('published', 1);
      }
  
  }
  </code></pre>
  <hr />
  <pre><code>class CourseUser extends Model
  {
  
      protected $fillable = [
          'course_id',
          'user_id',
          'event'
      ];
  
  }
  </code></pre>
  <hr />
  <pre><code>class SearchController extends ApiController
  {
  
      public function search(Request $request)
      {
          $results = Course::with('history')
              -&gt;published
              -&gt;where('title', 'like', $request-&gt;filter['title'])
              -&gt;where('description', 'like', $request-&gt;filter['description'])
              -&gt;get();
  
          if (! count($results) &gt; 0) {
              return $this-&gt;sendResponse(
                  __('No results for your query.'),
                  [
                      'code'=&gt;204,
                      'message'=&gt; __('There are no results for your search criteria.')
                  ],
                  204
              );
          }
          return new CourseCollection($results);
      }
  }
  </code></pre>