1

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 = [{},{}];

2 Answers 2

8

Eloquent has a built-in toJson method:

var obj = {
    users: <?php echo $users->toJson(); ?>
};
Sign up to request clarification or add additional context in comments.

1 Comment

that gives me var obj = [{},{}];
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.