stack stack - 16 days ago 5
PHP Question

How to open specific page of paginate?

I get comments paginated. And I need to check, if I have the id of a comment, then open the page that comment is in. Here is my code:

public function show_comments(Request $request) {
$cmnt_id = $request->input('cmnt_id');
if ( isset( $cmnt_id ) ){
// I need to get all comments paginated but start from the page that $cmnt_id is in it
} else {
// starts from page 1
$comments = Cmnt_tb::paginate(10);
}
return View('show_cmnts', compact('comments'));
}


How can I do that? any idea?

I think I have to make a new URL and redirect to it.

Answer

Maybe there is a better solution, but I guess something like this will work for you:

public function show_comments(Request $request) {
    $cmnt_id = $request->input('cmnt_id');
    $perPage = 10;
    if (isset($cmnt_id)){
        // Get row number.
        $rowNumber = Cmnt_tb::where('id', '<=', $cmnt_id)->count();
        // Get page.
        $page = ceil($rowNumber / $perPage);
        return redirect('show-comments-url?page='.$page);
    } else {
        $comments = Cmnt_tb::paginate($perPage);
        return view('show_cmnts', compact('comments'));
    }
}