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 ?
For example, before rendering a user profile, you need to fetch the user's data from the server. We can achieve this in two different ways: Fetching After Navigation: perform the navigation first, and fetch data in the incoming component's lifecycle hook. Display a loading state while data is being fetched.
Laravel is PHP's fastest-growing Framework with its ease of use, scalability, and flexibility. VueJS is the fastest growing Front end Library in the Javascript community. Laravel is providing VueJS support out of the box. So let us get up and running with the Laravel VueJS tutorial.
To access the laravel relationships in VUE component Laravel Eager loading works well. Use with () Method. for example, Thanks for contributing an answer to Stack Overflow!
Laravel comes with axios inbuilt when you had installed modules in previous article. It fetches the json data from controller and render it into ViewCategory.vue. If you want to fetch the data from database just execute query and send it via json. I hope this tutorial helps you.
Basic GET Requests with Fetch API and VueJS 1 Step 1: Create your API Request#N#For loading our transactions, I made 2 methods (one with the Fetch API and the other... 2 Step 2: Breaking Down the Method Signature#N#So these are very simple GET requests, we will get to the more advanced stuff... 3 Step 3: Breaking Down the Method Response More ...
You can also pass the data directly inside the Vue instance itself and since the Laravel blade template will be executed first, by the time the page load the data will already be present inside the Vue instance. new Vue ( { el: '#app', data () { return { posts: @json ($posts) } }, mounted () { console.log (this.posts); } })
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With