user391986
user391986

Reputation: 30906

laravel model object to string for javascript

Please help me clean this monstrosity! I'm trying to get my array of users from Laravel collection to a JavaScript variable.

This is the only way I got this working:

<script>
var obj = {
    users: [<?php for($i = 0; $i < count($users); $i++) { echo $users[$i]->getObject(); if ($i + 1 < count($users)) { echo ','; } } ?>],
}
</script>

which gives me the correct output:

users: [{"id":1,"first_name":"A","last_name":"A","birthday":"1970-02-12","gender":"M","username":"aa","email":"[email protected]","permissions":null,"activated":true,"activated_at":null},{"id":2,"first_name":"b","last_name":"b","birthday":"1982-01-10","gender":"M","username":"bb","email":"[email protected]"}]

I am using Robclancy/Presenter which means the object when sent to the view ends up being a presenter so I need to get the object back with $user->getObject();


From my controller $users = User::all(); which returns a Collection of User objects. enter image description here

I tried to do

<script>
var obj = {
    users: <?php echo $users; ?>,
}
</script>

but that just gives me

var obj = [{},{}];

Upvotes: 1

Views: 4507

Answers (2)

user391986
user391986

Reputation: 30906

Here is the solution, it was the issue with presenter not knowing how to convert the object, robclancy helped me out. https://github.com/robclancy/presenter/issues/18

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219936

Eloquent has a built-in toJson method:

var obj = {
    users: <?php echo $users->toJson(); ?>
};

Upvotes: 8

Related Questions