Q:

show paginate according to data in relation table in laravel

I'm going to create blog in Laravel. Now I get post form category in the blog and I can only show paginate according to post but I want to show paginate only for posts that have relations with category id
I have some problem in my code, please help me to fix my problem.
In the controller source code:
//this code show posts according to category id
$postCatId = $request->postCatId;
$postList =PostCat::with("posts")->where('id',$postCatId)->get();

//this code show paginate according to posts has relation with category
$paginate=PostCat::with("posts")->where('id',$postCatId)->paginate(2);

This then returns $postList and $paginate to view
in View:
//show posts has relation with category id
@foreach($PostList as $post)
     @foreach($post->posts as $post_item)
     {{$post_item->id}}
     @endforeach
@endforeach

//show paginate according to posts has relation with category id
{{$paginate->links()}}

But I cannot show paginate with posts that has relation with category id

A:

If you want to paginate posts that have a category, use this query instead of two current ones:
$posts = Post::with('category')
             ->has('category')
             ->where('id', $postCatId)
             ->paginate(2);

Make sure you have category() relationship in the Post model:
public function category()
{
    return $this->belongsTo('App\PostCat');
}

In a view iterate over $posts and render links:
@foreach($posts as $post)
    <div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div>
@endforeach

{{ $paginate->render() }}

