Skip to content
Advertisement

Add Pagination to relationship and get the relationship’s relationship – Laravel

I am building a forum website using Laravel and Vue.

I have three tables: forums, posts, and users. One forum can have multiple posts, each post has a user who created the post.

When the user clicks on one forum, I want to display the latest 10 posts to this forum with the paginate method.

Forum.php

JavaScript

Post.php

JavaScript

User.php

JavaScript

Here I retrieve the forum posts with the users.

ForumService.php

JavaScript

However, I want to retrieve only 10 posts and get each post’s user, so how do I do that in a relationship? The posts are paginated, but how to I get now the posting user? Because the dot syntax is applying to the user, therefore I paginate the user, not the posts.

ForumService.php

JavaScript

Advertisement

Answer

Just add the with method inside the query scope of the function you have created.

JavaScript

Now you can access the first user with $forum->posts[0]->user which will not query to the database but will prefetch the users and populate it in paginator collection.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement