title: How to count items where foreign key is repeated?
body: <p><strong>How I can count items with same foreign key and still get acces to relationship data?</strong></p>
  
  <p>I'm using <strong>PHP</strong> - <strong>Laravel</strong> - <strong>Eloquent</strong>, and have three tables: <code>User</code>, <code>User_items</code> and <code>items</code>.</p>
  
  <p><code>User_items</code> has three columns: <code>id</code>, <code>user_id</code> and <code>item_id</code>:</p>
  
  <pre><code>ID | user_id | item_id
  0  | 5       | 2  
  1  | 5       | 3  
  2  | 5       | 8  
  3  | 5       | 3  
  </code></pre>
  
  <p>Let's say <code>items</code> also has three columns: <code>id</code>, <code>name</code> and <code>value</code>:</p>
  
  <pre><code>ID | Name    | Value
  2  | Sword   | 500  
  3  | Pickaxe | 250  
  8  | Shovel  | 700  
  </code></pre>
  
  <p>I want to count items with the same <code>user_id</code> and return item data from the <code>items</code> table. In order to get all of the user items, I'm using the following relationship:</p>
  
  <pre><code>    public function user_items()
      {
          return $this-&gt;hasMany(User_items::class, 'user_id', 'id');
      }
  </code></pre>
  
  <p>Next, I want to get the names of these items and count them. I don't just want:</p>
  
  <pre><code>Sword
  Pickaxe
  Shovel
  Pickaxe
  </code></pre>
  
  <p>I want, somehow, to get the results like this:</p>
  
  <pre><code>2 Pickaxe
  1 Sword
  1 Shovel
  </code></pre>
  
  <p>My <code>user_items</code> relationship, to get the data about an item looks like :</p>
  
  <pre><code>    public function item_data()
      {
          return $this-&gt;hasOne(Items::class, 'id', 'item_id');
      }
  </code></pre>
  
  <p>Thats how I'm getting repeatable result:</p>
  
  <pre><code>return response()-&gt;json(["DATA" =&gt; $user-&gt;user_items-&gt;load('item_data')-&gt;toArray()], 201);
  </code></pre>
  
  <p>Example output</p>
  
  <pre><code>   "DATA":[  
        {  
           "id":1,
           "item_id":5,
           "created_at":"2019-06-04 08:44:08",
           "updated_at":"2019-06-04 08:44:08",
           "item_data":{  
              "id":5,
              "name":"Sword",
              "rarity":"good",
              "value":500,
              "image":"image.jpg",
              "color":"#3160ed",
              "created_at":null,
              "updated_at":null
           }
        },
  }
  </code></pre>
  
  <p>I want to add a row like <code>"count": 5</code> to the above output.</p>