[Vuejs]-Difficult to get associate table's record in Vuejs from Laravel collection

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>

Leave a comment