vinoth06's avatar

Pagination for Relationship

Hi,

I have a Post | Category | User tables.

Each post has categories by the user.

Now I want to show the Category page, which will show the list of posts belongs to that Category along with the user detail of that post.

How to add pagination for Posts.

I tried with,

=Try 1: I couldn't get the user details of that particular post=
public function single( Category $slug ) {
    return $slug->posts()->paginate('2');
}

=Try 2:  I can get the post by pagination along with the user, but there are no pagination details.=
public function single( Category $slug ) {
        return $category = $slug->load( [
            'posts' => function ( $q ) {
                $q->latest()->paginate('2');
            },
            'posts.user'
        ] );
}

How to solve this issue. Please guide me.

0 likes
2 replies
DC Blog's avatar

This is the way I've done it before in a controller:

$posts = Post::with('category')->whereHas('category', function($query) use ($slug) {
        $query->where('slug', '=', $slug);
    })->paginate();
vinoth06's avatar

Hi,

Thanks for your code,

After applied, I will get all categories associated with that post, But I need only the category where I passed Category $slug

The above code works like Post::with( ['user','categories' ] );

FYI, Post, and Categories are connected with Pivot like category_post

Please or to participate in this conversation.