1

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?

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. Is there anyway I can loop over and display all the roles a given user has? I'm not sure how this is done with the current implementation in Vue.
Just use v-for in the same way you did for each user, but instead for each role.
Oh, didn't know it was that simple. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.