I'm trying to display data with a relationship (using many-to-many) within my Vue component.
I store users in object from rest API:
users: {},
//...
axios.get("api/user").then(({data}) => (this.users = data));
An example of JSON returned from api/user
:
{"current_page":1,"data":[{"id":2,"name":"Andrew","description":"Testing","role":[{"id":2,"role_title":"TestTitle","pivot":{"user_id":2,"role_id":2}}
When displaying the data I can do
<tr v-for="user in users.data" :key="user.id">
<td>{{user.name}}</td> // DOES work, displays 'Andrew'
However if I try to do:
<td>{{user.role.role_title}}</td> //does NOT work, should display 'TestTitle'
It displays nothing, what am I doing wrong?
user.role
is an array of roles. To display the first role (assuming there will always be at least one role) you can do:
<td>{{ user.role[0].role_title }}</td>