Question

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?

Pas de solution correcte

Autres conseils

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

json_encode($invoices->toArray());
enter code here

Also, you may only pass the data array like:

json_encode($invoices->toArray()['data']);

Or this:

$invoices = $invoices->toArray();
json_encode($invoices['data']);

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);
json_encode($user->toArray());

Output:

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":"heerasheikh@ymail.com","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":"http://blog.dev/images/user_1/profile_image/heera_new'... (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:

->toJson();

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:

<script>
var pzFieldArray = {{ $invoices }}
</script>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top