title: Laravel: Historical ranking system with ManyToMany relationship
body: <p>I would like to display a page where Users are listed by their Rank. A Rank can have multiple Users (for example, 2 Users can be at the 2nd place) and a User can have multiple Ranks too, because I would like to keep an historic of Users and Ranks through time.</p>
  
  <p>Here's <code>User.php</code>
  
  
  
  <pre class="lang-php prettyprint-override"><code>namespace App;
  
  use Illuminate\Foundation\Auth\User as Authenticatable;
  
  class User extends Authenticatable
  {
      // ...
  
      public function Ranks() {
          return $this-&gt;belongsToMany('App\Rank');
      }
  }
  </code></pre>
  
  <p>And <code>Rank.php</code>
      
  
  <pre class="lang-php prettyprint-override"><code>namespace App;
  
  use Illuminate\Database\Eloquent\Model;
  
  class Rank extends Model
  {
      public $timestamps = false;
  
      public function Users() {
          return $this-&gt;belongsToMany('App\User')-&gt;withPivot('created_at');
      }
  }
  </code></pre>
  
  <p>I also have a <code>rank_user</code> table in my database, with <code>id</code>, <code>rank_id</code>, <code>user_id</code> and <code>created_at</code> fields.</p>
  
  <p>This is how I record it in database:</p>
  
  <pre class="lang-php prettyprint-override"><code>$user-&gt;ranks()-&gt;attach($rank_id, ['created_at' =&gt; Carbon::now()-&gt;addMinutes(105)]);
  </code></pre>
  
  <p>In order to list users by rank, and I mean at the current (most recent) rank, this is what I have:</p>
  
  <pre class="lang-php prettyprint-override"><code>$ranks = Rank::with('users')-&gt;get();
  </code></pre>
  
  <p>For example, for the 1st rank, it gives me all users who have been at the 1st place since the beginning instead of giving me all users who <strong>currently</strong> are at the first place.</p>
  
  <p>I don't know how to limit the query to the most recent date.</p>