Khudadad's avatar

Eloquent pagination

How do I paginate the result of this Eloquent

 public function show($slug)
{
    $post = Post::where('slug',$slug)->with(['user','comment'])->first();
    return view('discuss.posts.show',compact('post'));
}

When the comments about the specfied post is getting more than 10 should be paginated. Thanks

0 likes
7 replies
bobbybouwmann's avatar

You can do it like this

$post = Post::where('slug', $slug)->with('user')->first();
$comments = Comment::where('post_id', $post->id)->paginate();

return view('discuss.posts.show',compact('post', 'comments));

And then in your view you can do something like this

{!! $comments->render() !!}
Khudadad's avatar

Thanks @bobbybouwmann for the reply, but it's not working as expected, I specified 5 comments per page of 9 comments, but all comments are shown per each page, it paginates 2 pages with all 9 comments per page.

joedawson's avatar
Level 18

It looks like you'll just need to change your $post->comments to $comments in your foreach.

@foreach($post->comment as $comment)
    {{-- Display the comment --}}
@endforeach

You want to reference the paginated comments, rather than the entire collection of comments you're currently referencing.

@foreach($comments as $comment)
    {{-- Display the comment --}}
@endforeach
1 like

Please or to participate in this conversation.