randm's avatar
Level 6

How to get the paganation info in array

I need to display the pagination info only as array. I tried to use toArray() method, but it include the data which I don't really need. So I tried to remove the data key from the array but I don't like the fact that i have to cast the model to array then remove it. I am hoping there is an easier way to do this without having to cast the data then removing it.

Here is my code.

    public function index()
    {
        $posts = Post::paginate(25);

        $data = [];

        foreach($posts as $post)
        {
            $data[] = $post->getApiData();
        }

        $paginate = $posts->toArray();
        unset($paginate['data']);

        return response()->json([
            'success' => true,
            'message' => 'Posts retrieved successfully',
            'data' => $data,
            'paginate' => $paginate
        ]);
    }
0 likes
1 reply
shez1983's avatar

whats this: $post->getApiData(); what are you doing here and is this really an API call?

to answer your question probably not.. this is easy.. its a two line (can condense to one line).. for now leave it..

Please or to participate in this conversation.