The issue is it doesn't work.

To clarify, if I perform the following:

$invoices = DB::connection(MY_CONNECTION)->table('invoice')->get();

And then pass it to a blade view, I can output it like this:

var pzFieldArray = {{ json_encode($invoices) }} 

This will produce an array of data in javascript. This tells me that the connection works fine.

However, if I perform the following:

$invoices = DB::connection(MY_CONNECTION)->table('invoice')->paginate(10);

And pass that to the same view, then I get an empty javascript array.

My question is simple: what am I doing wrong?

No correct solution


You may use this with paginate(), it returns an instance of Illuminate\Pagination\Paginator:

enter code here

Also, you may only pass the data array like:


Or this:

$invoices = $invoices->toArray();

So, only data (records) will be encoded but other properties won't be available in the json, in this case you may need all properties such as tota, per_page etc. An example of json encode data:

$user = User::paginate(5);


string '{"total":10,"per_page":5,"current_page":1,"last_page":2,"from":1,"to":5,"data":[{"id":1,"first_name":"Sheikh","last_name":"Heera","username":"heera","email":"","role_id":1,"bio":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.","profile_picture":"'... (length=2618)

Update: Well, it could be done using toJson() directly as well (I missed it):

return Invoices::paginate(10)->toJson();

Sheikh Heera was correct in that paginate itself wouldn't do the task. However, there is an easier way. All I need to do is add the following to the paginate line:


The full line will now read:

$invoices = DB::connection(MY_CONNECTION)->table('invoice')->paginate(10)->toJson();

And you can convert it to javascript simply:

return Response::json($invoices);

This works when you are doing Ajax calls, but if you want to include it in a view, its just a simple:

var pzFieldArray = {{ $invoices }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top