title: Get count of related model in laravel
body: <p>Suppose I need to get a Post with the count of Comments. There are of course a number of ways of doing this. What is the best (or preferred) way of doing this?</p>
  
  <ol>
  <li>Eager Load + then with route model binding to get count whenever Model is injected in route.</li>
  </ol>
  
  <pre><code>class Post extends Model {
  
      protected $withCount = [ 'comments' ];
  
      public function comments() 
      { 
           return $this-&gt;hasMany();
      }
  
  }
  </code></pre>
  
  <pre><code>Route::get('/posts/{post}', function (App\Post $post) {
  
      return $post;  // $post→comments_count gives count.
  
  } 
  </code></pre>
  
  <ol start="2">
  <li>Cache the count</li>
  </ol>
  
  <pre><code>public function getCachedCommentsCountAttribute()
  {
      return Cache::remember($this-&gt;getTable() . '.' . $this-&gt;getKey() . '.comments_count', 60*60*24, function () {
          return $this-&gt;comments()-&gt;count();  // posts.{id}.comments_count
      }); 
  }
  
  </code></pre>
  
  <ol start="3">
  <li>Other </li>
  </ol>
  
  <p>What would be best performance wise?</p>