Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ifrit's avatar
Level 2

Creating pagination

I'm trying to create a comment section that has pagination. The error I'm getting is this

FatalErrorException in OpenController.php line 118: Call to a member function paginate() on array

My OpenController

<?php

namespace App\Modules\Open\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Input;
use Validator;
Use Mail;
use Response;
use App\Modules\Menus\Models\Menu;
use App\Modules\Authors\Models\Story;
use App\Modules\Authors\Models\Comment;
use App\Modules\Seo\Models\Seo;
use PDF;
use App;
use DB;
use Dompdf\Dompdf;
use Illuminate\Pagination\LengthAwarePaginator;

class OpenController extends Controller
{
    public function slug($slug){
        $menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
        $stories = Story::where('slug', $slug)->get();

        $slug = $slug;
        
        $story = Story::with('author')->where('slug', $slug)->first();

        $name = $story->author->first()->name;
        $surname = $story->author->first()->surname;
        
        $comment = Story::with('comment')->where('slug', $slug)->first();
        $test = $comment->comment->toArray()->paginate(2);

        $pdf = Story::all();


        return view('open::public.single-story', compact('menus_child', 'gh', 'object', 'pdf1', 'pdf_sigh', 'load', 'stories', 'slug', 'test', 'name', 'surname'));
    }
}

Line 118 is

$test = $comment->comment->toArray()->paginate(2);
0 likes
5 replies
tykus's avatar

The error is self-explanatory; don't use toArray() before calling paginate(); in fact, don't call paginate() on a Collection as it is a Builder method.

Ifrit's avatar
Level 2

So where would the best place be to put paginate() When I did this

$test = $comment->paginate(2)->comment->toArray();

I got this error

ErrorException in OpenController.php line 118: Undefined property: Illuminate\Pagination\LengthAwarePaginator::$comment

When I did this

$test = $comment->comment->paginate(2)->toArray();

I got this error.

BadMethodCallException in Macroable.php line 74: Method paginate does not exist.

And then I did this

$comment = Story::with('comment')->where('slug', $slug)->paginate(2)->first();

added comment to my compact and did this in my view

{!! $comment->links() !!}

and I got this error

ErrorException in Builder.php line 2445: Call to undefined method Illuminate\Database\Query\Builder::links() (View: C:\xampp\htdocs\writers-circle\app\Modules\Open\Resources\Views\public\single-story.blade.php)
tykus's avatar
tykus
Best Answer
Level 104

Try this (using more appropriate variable names):

$story = Story::where('slug', $slug)->first();
$comments = $story->comment()->paginate(2);

Please or to participate in this conversation.