A
A
Alexander Shapoval2017-05-07 14:09:23
Laravel
Alexander Shapoval, 2017-05-07 14:09:23

Laravel pagination() and API response. Why is an array returned and not an object?

Tell me why when I write:

$books = BookModel::paginate($take, $offset);

$books = $books->each(function ($book) {
    $book->setLink();
    $book->setFileSize();
});

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

Is it returning a normal array of data, not a paginate object? Please tell me how to solve this problem. Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Shapoval, 2017-05-07
@AlexanderShapoval

The main mistake was overwriting $books. It was necessary like this:

$books = BookModel::paginate($take, $offset);

$books->each(function ($book) {
    $book->setLink();
    $book->setFileSize();
});

return response()->json(['response' => $books->toArray()], 200);

P
pantagruel964, 2017-05-07
@pantagruel964

toJson method. Have you read the doc?
https://laravel.com/docs/5.4/pagination#converting...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question