title: Eloquent Filter by relationship (ONLY last record)
body: <p>I edit my question to be more explicative</p>
  
  <p>I need to build a scope for filtering a hasMany relationship. The problem is, I want to apply that query to <strong>last</strong> item <strong>ONLY</strong>, I mean, I want my Model filtered by a column of an specific record of a HasMany relationship, is it possible?</p>
  
  <p>Context: An App that have Posts, each Posts have many Statuses to keep an historic. I want to filter the Posts by the <strong>last Status</strong> of each one.</p>
  
  <p>Posts:</p>
  
  <pre><code>{
      public function statuses() 
      {
          return $this-&gt;hasMany(Status::class); // Only last one is important for querying
      }
  }
  </code></pre>
  
  <p>Then, in an scope, I would like to do something like this:</p>
  
  <pre><code>public function scopeIsActive(Builder $builder)
  {
      return $builder-&gt;whereHas('statuses', function(Builder $q) {
          // How to apply this ONLY to last created record???
          return $q-&gt;whereDate('activation', '&lt;=', today());
      });
  }
  </code></pre>
  
  <p>And that's all! </p>
  
  <p><strong>Edit: (Solved query)</strong></p>
  
  <p>After some digging I solved my problem with this:</p>
  
  <pre><code>public function scopeIsActive(Builder $builder)
  {
      return $builder-&gt;whereHas('statuses', function (Builder $q) {
          return $q-&gt;whereDate('activation', '&lt;=', today()) // applies to all
              -&gt;where('statuses.id', function ($sub) { // applies to specific one
              return $sub-&gt;select('id')
                  -&gt;from('statuses')
                  -&gt;whereColumn('post_id', 'statuses.id')
                  -&gt;latest()
                  -&gt;limit(1);
          });
      });
  }
  </code></pre>