How to return pivot data of a many-to-many relationship?

Ad

How can I select pivot data (col1 and col2) for roles of user with id=2?

+------------+
|    User    |
+------------+
| id | name  |
+----+-------+
| 1  | John  |
+----+-------+
| 2  | Brian |
+----+-------+

+------------+
|    Role    |
+------------+
| id | title |
+----+-------+
| 1  | Admin |
+----+-------+
| 2  | Owner |
+----+-------+

+-----------------------------------+
|              UserRole             |
+-----------------------------------+
| user_id | role_id |  col1 |  col2 |
+---------+---------+-------+-------+
|    2    |    1    | lorem | dolor |
+---------+---------+-------+-------+
|    2    |    2    | ipsum |  amet |
+---------+---------+-------+-------+

I can use User::find(2)->roles but it returns:

[
  {
    "id": 1,
    "title": "Admin",
    "pivot": {
      "user_id": 2,
      "role_id": 1,
      "col1": "lorem",
      "col2": "dolor"
    }
  },
  {
    "id": 2,
    "name": "Owner",
    "pivot": {
      "user_id": 2,
      "role_id": 2,
      "col1": "ipsum",
      "col2": "amet"
    }
  }
]

How can I change the query to only have the following result (only pivot data):

[
  {
    "user_id": 2,
    "role_id": 1,
    "col1": "lorem",
    "col2": "dolor"
  },
  {
    "user_id": 2,
    "role_id": 2,
    "col1": "ipsum",
    "col2": "amet"
  }
]
Ad

Answer

Ad

You can use pluck() to achieve this.

https://laravel.com/docs/5.3/collections#method-pluck

User::find(2)->roles->pluck('pivot');

Hope this helps!

Ad
source: stackoverflow.com
Ad