George12's avatar

Return pagination in array

I need to return a json with all products and stores.

I tried this

$products = $products->paginate(20);
$stores=$this->getStores();
return ['product'=> $products, 'stores' =>$stores];

and this

return Response::json(
  array(
    'products' => $products,
    'stores' => $stores,
  ), 200
);

but $products returns empty. (If i run "dd($products)" i can see the results)

Is there something i can do? Why laravel doesn't let me have the pagination in an array?

0 likes
5 replies
jlrdw's avatar

First of all you should be getting the results from the database with pagination not putting everything into an array first.

George12's avatar

@jlrdw No sure what you are trying to say. I am getting the data from the database and then paginate them before sending them to the view.

bobbybouwmann's avatar

You need to paginate the query, not the collection. Can you show your query?

You need to do something like this

Products::paginate(20); // This works, paginate will run the query

Products::all()->paginate() // This won't work, paginate can't be called on the collection

Products::where('published', 1)->get()->paginate() // This won't work, paginate can't be called on the collection
George12's avatar

Yes, of course. I already said that i have a query which is getting the data from the database correctly. This is my query, although it works fine, and there is no reason to post it. :)

    $stores=Store::all();
        $products = Product::where('name', 'like', '%' . Input::get('keyword') . '%')->where('phone_id', 0);

The problem occurs when i paginate the query AND send it to the view inside an array.

So if i return this, everything works fine.

return $products->paginate(20);

BUT if return this, products are empty (but stores are fine)

$products=$products->paginate(20);
return [
'products' => $products,
'stores'=> $stores
];
thomaskim's avatar
Level 41

@Chrysanthos Use either the toArray or toJson methods, depending on what you need. For example:

$products = $products->paginate(20)->toArray();
return [
    'products' => $products,
    'stores'=> $stores
];
2 likes

Please or to participate in this conversation.