1

I'm using Vuejs and Laravel building a live feed app, but i found that it is difficult to get associate data from collection in Vuejs, is there anyway to get those data easily?

Here is my attempt:

<div class="sl-item" v-for="post, index in posts">
      <a href="javascript:void(0)">
        <div class="sl-content">
          {{post}}
          <br>
          ------------------------
          <br>
          {{getUser(post.user_id)}}
        </div>
      </a>
    </div>

Here is my methods that i intend to retrieve user record:

methods: {
    getUser (id)
    {
      return axios.get("/user/getUser/" + id)
      .then(response => {
        console.log(response.data);
        return response.data;
      });
    }
  },

But this is what i got: enter image description here

I can log what i get in console, but i can't display or access the thing i return from my method.

enter image description here

Is there any other easier way to achieve this?

1 Answer 1

0

You fetching all the data from collection. that's why you also getting unwanted data in your object

in your current situation (without changing in your controller script) you can access those data as like:

public function index(Request $request)
{
    if ($request->ajax()) {
        return Post::with(['user' => function($query){
           $query->select(['id', 'name'])
        }])
            ->select(['id', 'title', 'description'])
            ->get;
    }
}

if you do this in your controller, then in your vue file,

data:function(){
        return{
            posts: [],
        };
    },
methods: {
    getPosts ()
    {
      return axios.get("/posts")
      .then(response => {
        this.posts = response.data;
      });
    }
  },

and in component:

<div class="sl-item" v-for="post, index in posts">
      <a href="javascript:void(0)">
        <div class="sl-content">
          {{post.title}}
          <br>
          ------------------------
          <br>
          {{ post.user.name }}
        </div>
      </a>
    </div>
Sign up to request clarification or add additional context in comments.

Comments

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.