title: laravel model object to string for javascript
body: <p>Please help me clean this monstrosity! I'm trying to get my array of users from Laravel collection to a JavaScript variable.</p>
  
  <p>This is the only way I got this working:</p>
  
  <pre><code>&lt;script&gt;
  var obj = {
      users: [&lt;?php for($i = 0; $i &lt; count($users); $i++) { echo $users[$i]-&gt;getObject(); if ($i + 1 &lt; count($users)) { echo ','; } } ?&gt;],
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>which gives me the correct output:</p>
  
  <pre><code>users: [{"id":1,"first_name":"A","last_name":"A","birthday":"1970-02-12","gender":"M","username":"aa","email":"a@a.com","permissions":null,"activated":true,"activated_at":null},{"id":2,"first_name":"b","last_name":"b","birthday":"1982-01-10","gender":"M","username":"bb","email":"b@b.com"}]
  </code></pre>
  
  <p>I am using <a href="https://github.com/robclancy/presenter" rel="nofollow noreferrer">Robclancy/Presenter</a> which means the object when sent to the view ends up being a presenter so I need to get the object back with <code>$user-&gt;getObject();</code></p>
  
  <hr>
  
  <p>From my controller <code>$users = User::all();</code> which returns a Collection of User objects.
  <img src="https://i.stack.imgur.com/YrzWw.png" alt="enter image description here"></p>
  
  <p>I tried to do </p>
  
  <pre><code>&lt;script&gt;
  var obj = {
      users: &lt;?php echo $users; ?&gt;,
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>but that just gives me</p>
  
  <pre><code>var obj = [{},{}];
  </code></pre>