Add some data in laravel paginate

You can create collection with custom data manually and use merge() helper:

$book = Data::where('userId','1')->paginate(3);

$custom = collect(['my_data' => 'My custom data here']);

$data = $custom->merge($book);

return response()->json($data);

Just checked, it works just fine.


The paginate function will return an object of the type Illuminate\Pagination\LengthAwarePaginator, it is not possible to just add another field to this.

I think the best solution for you would be to add the pagination object and the other values in an array and convert this array to json. This way your books data is seperated from the other data you want to add.

Like so:

return response()->json([
    'books' => $books,
    'foo' => 'bar'
]);

In this case your json object will look like this:

{
    books: {
        // Pagination object with books
    }
    foo: 'bar'
}

If you use the Illuminate\Pagination\LengthAwarePaginator class "manually", there's the option of extending it and overriding the toArray method:

return new class(
    $collection,
    $count,
    $limit,
    $page,
    // https://github.com/laravel/framework/blob/6.x/src/Illuminate/Pagination/LengthAwarePaginator.php#L40
    // values here will become properties of the object
    [
        'seed' => $seed
    ]
) extends LengthAwarePaginator {
    public function toArray()
    {
        $data = parent::toArray();
        // place whatever you want to send here
        $data['seed'] = $this->seed;
        return $data;
    }
};

Result

current_page    1
data    []
first_page_url  "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
from    null
last_page   1
last_page_url   "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
next_page_url   null
path    "/finder"
per_page    20
prev_page_url   null
to  null
total   0
seed    0.2 // <-- our custom prop

There's some extra work involved with instantiating LengthAwarePaginator yourself, but it gets the job done.