Search code examples
phplaravellaravel-5eloquentlaravel-5.3

Laravel 5.3 - Eloquent get paginated collection from certain point with id?


For a blog post, given post_id of 4 which has 1000 comments, I can get comment_id of 400 using eloquent like this:

$comment = Comment::where('id', 400)->where('post_id', 4)->first();

The question is, how can I get for that same post, the chunk of 10 comments starting with comment_id 400 with the previous 9 comments (for a total of 10).

This is for pagination starting from a certain point in the comments, in this case 400. If there are any comments before/after 400 for this post, I would need the previous/next pagination urls if they exist.

So for example, 400 has more comments around it for this post, so I should get back comments with comment_id 400 - 390 from eloquent, with this pagination (pseudo code):

next_page_url: "http://laravel.app?page=61",
prev_page_url: "http://laravel.app?page=59"

What would the eloquent query to handle this situation in laravel be?


Solution

  • I'm not sure why you would do it based on ID - I'd simply push it back 400 spots. However, here:

    Comment::where('id', '<', 400)->orderBy('id', 'desc')->take(10)->get();
    

    This will get you the 10 previous comments.