1
votes

I have a comments list with a per_page input field that allows users to show more comments on the page via ajax. By default, it's set to 50

But when I try to change it, say to 25, I get this errors in the developer's console

POST http://localhost/r2/public/posts/per_page 500 (Internal Server Error)

And in the Network tab, I can see this error

ErrorException in LengthAwarePaginator.php line 48:

Division by zero

in LengthAwarePaginator.php line 48

at HandleExceptions->handleError('2', 'Division by zero', 'C:\xampp\htdocs\r2\vendor\laravel\framework\src\Illuminate\Pagination\LengthAwarePaginator.php', '48', array('items' => array(), 'total' => '0', 'perPage' => null, 'currentPage' => '1', 'options' => array('path' => 'http://localhost/r2/public/posts/per_page', 'query' => array()), 'key' => 'query', 'value' => array())) in LengthAwarePaginator.php line 48

at LengthAwarePaginator->__construct(array(), '0', null, '1', array('path' => 'http://localhost/r2/public/posts/per_page', 'query' => array())) in CommentController.php line 51

at CommentController->paginate(array(), null, object(Request), object(Post)) in CommentController.php line 57

at CommentController->comment_list(null, object(Request), object(Post)) in CommentController.php line 153

at CommentController->show_comment_list(object(Request), object(Post)) in CommentController.php line 164

at CommentController->per_page(object(Request), object(Post), 'posts')

It was working fine before I changed its route to integrate it with the posts page.

My Routes

Route::get('{post}/comment', ['as' => 'comment', 'uses' => 'CommentController@index']);
Route::post('{post}/post_this_comment', 'CommentController@post_this_comment');
Route::get('{post}/recaptcha', 'CommentController@recaptcha');
Route::get('{post}/reply_comment', 'CommentController@reply_comment');

// this is the per_page route
Route::post('{post}/per_page', ['as' => 'per_page', 'uses' => 'CommentController@per_page']);

Route::post('{post}/comment/update', ['as' => 'comment/update', 'uses' => 'CommentController@update']);

And this is the CommentController

private function paginate($items, $perPage, Request $request) {
    $page = Input::get('page', 1); // get current page or default to 1
    $offset = ($page * $perPage) - $perPage;
    return new LengthAwarePaginator(
        array_slice($items, $offset, $perPage, false),
        count($items),
        $perPage,
        $page,
        ['path' => $request->url(), 'query' => $request->query()]);
}

protected function comment_list($per_page, Request $request, Post $post) {
    $root_comments = Comment::root_comments($post->id);
    $root_with_replies = $this->include_replies_for($root_comments);
    $paginated_comments = $this->paginate($root_with_replies, $per_page, $request, $post);
    return $paginated_comments;
}

protected function show_comment_list(Request $request, Post $post) {
    $per_page = Input::get('per_page');
    session(['per_page' => $per_page]);
    $comment_list = view('eastgate.comment.comment_list')
                        ->with('comments', $this->comment_list($per_page, $request, $post))
                        ->with('total_comments', $this->total_comments())
                        ->with('per_page', $per_page)
                        ->render();
    return $comment_list;       
}

public function per_page(Request $request, Post $post){
    $response = array(
        'status' => 'success',
        'msg'   => 'reply comment',
        'comment_list' => $this->show_comment_list($request, $post)
    );
    return Response::json($response);       
}

This is the JS and HTML

$(document).on('change', 'input.comments_per_page', function(){
    var formData = new FormData();
    formData.append('per_page', $('.comments_per_page').val());
    var request = $.ajax({ // push question data to server
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'per_page', // the url where we want to POST
        data        : formData, 
        dataType    : 'json',
        processData : false,
        contentType : false
    });
    request.done(per_page_done_handler);
    request.fail(per_page_fail_handler); // fail promise callback   
});

<div class="col-xs-12">
    Show <input type="text" name="comments_per_page" class="comments_per_page" value="{!! $per_page !!}" size="2" title="Number of comments per page"> comments per page
</div>

UPDATE

I should mention that I can also see the default pagination div of laravel, and when I click on the second page which has the url of http://localhost/r2/public/posts/2/?page=2 the page redirects to http://localhost/posts/2?page=2 and I get this error

ERROR 404 Object not found!

But if I manually go to this URL http://localhost/r2/public/posts/2?page=2

The second page with the comments loads just fine.

UPDATE 2

I just setPath on $paginated_comments in comment_list() method and now next pages are opening fine. but still getting the Division by zero error when I try to change the number of comments shown.

$paginated_comments = $this->paginate($root_with_replies, $per_page, $request, $post);
$paginated_comments->setPath('');
2

2 Answers

5
votes

It's not matter in per_page number (50 or 25). If you look at \vendor\laravel\framework\src\Illuminate\Pagination\LengthAwarePaginator.php, you can see your problem line ( it throws exception Division by zero) :

$this->lastPage = (int) ceil($total / $perPage); // <= problem

It means only one thing - $perPage is 0 or null => you don't pass expected value for per_page (25) to LengthAwarePaginator constructor. You need check var per_page statement in order methods per_page() => show_comment_list() => comment_list() => paginate().

P.S. imho, it should be one single action for pagination. You have all required info to make it, however, you divide it on four "parts".

1
votes

I think that your problem is that you are not telling to your route that per_page is a parameter, let me explain :

Route::post('{post}/per_page', ['as' => 'per_page', 'uses' => 'CommentController@per_page']);

Should be : {per_page}

Route::post('{post}/{per_page}', ['as' => 'per_page', 'uses' => 'CommentController@per_page']);

I hope this can help you.