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

HeinZawHtet's avatar

Sort result with custom function and paginate

Hi, I want to sort results with custom function and want to paginate the result.

I try this. EG :

$posts = Post::paginate(3)->sortBy(function ($post) {
    // custom sort here
});

It 's work . But when i show pagination in views with $posts->render();. It said "Method render does not exist".

How to sort with custom function and paginate properly. Is there any better ways to do it?

0 likes
3 replies
zachleigh's avatar

Create the paginator after you sort the results. Try this:

$posts = Posts::all()->sortBy(function ($post) {
    // custom sort here
})->paginate(3);
1 like
zachleigh's avatar

Hmm. Maybe you could manually create one. Something like this:

    private function paginateAnswers($data, $request)
    {
        $page = $request->get('page', 1);

        $perPage = 10;

        $offset = ($page * $perPage) - $perPage;

        $paginator = new LengthAwarePaginator(
            $data,
            count($answers),
            $perPage,
            $page,
            ['path' => $request->url(), 'query' => $request->all()]
        );

        return $paginator;
    }

Please or to participate in this conversation.