7

How can I show the user name in my table using vuejs ?

I have my users and posts table with the relationships set. A user has many posts and a post belongs to a user.

In my Posts.vue template I can now show the post table data:

<tr v-for="post in posts">
    <td>{{ post.id }}</td>
    <td>{{ post.title }}</td>
    <td>{{ post.body | snippet }}</td>
</tr>

A script looks like this:

<script>
    export default {
        data(){
            return{
                posts: []
            }
        },

        methods: {
            showPosts(){
                axios.get('/app/posts').then(response => {
                    this.posts = response.data.posts;
                });
            }
        },
       mounted(){
            this.showPosts();
       }
    }
</script>

My PostController looks like this in the index function

 public function index()
 {
    //
    $posts = Post::all();
    return response()->json([
        'posts' => $posts,
    ], 200);
 }

Since I have the user_id in the posts table, How can I show the user name in my table using vuejs ?

Sidney Sousa
  • 3,378
  • 11
  • 48
  • 99

3 Answers3

24

So I found from Laravel docummentation that I could pass the "with" function in my controller like this:

$posts = Post::with('user')->get();

That gives me the posts and the user data of that post as well which allows me to access like this:

{{ post.user.name }}
Sidney Sousa
  • 3,378
  • 11
  • 48
  • 99
1

Thanks for documenting this, it sure helps.

I was doing a relational linking in laravel, not ready with the api yet but with the with() method, referencing the relational data was a breeze in my vuejs code.

Not Working: Laravel

public function index()
{
  if (request()->q){
    $search = request()->q;

    $searches =  User::whereHas('doctor') 
      ->where(function ($query) use ($search){
        $query->where('name', 'like', "%$search%")
              ->orWhere('email', 'like', "%$search%");
      })->paginate(5);
  }

  return $searches;
}

Working: Laravel

public function index()
{
  if (request()->q){
    $search = request()->q;

    $searches =  User::with('doctor')->whereHas('doctor') 
      ->where(function ($query) use ($search){
        $query->where('name', 'like', "%$search%")
              ->orWhere('email', 'like', "%$search%");
      })->paginate(5);
  }
  return $searches;
}

Usage: VueJs

... <span v-text="search.doctor.specialty"></span>

Ayeni TonyOpe
  • 1,651
  • 2
  • 12
  • 6
1

To access the laravel relationships in VUE component Laravel Eager loading works well. Use with() Method. for example,

public function recent_orders() {

     $orders = Order::with('service')->where('user_id', Auth::User()->id)->get();

     return response()->json($orders);
}

Now to access the relationship we can write,

<p>{{ order.service.name }}</p>
Murad
  • 1,064
  • 16
  • 13