title: Is there a good "Laravel way" to escape html when returning json results?
body: <p>I feel like this should be a common problem, but I haven't been able to find an answer for it.  Blade templates make escaping html easy with <code>{{ $variable }}</code>, but for outputting json to an ajax request, not so much.</p>
  
  <p>Naturally, I work with an app that does a lot of ajax calls for user inputted data and returns the results as JSON to the client, which renders it in a jQuery DataTable.  So consider this scenario:</p>
  
  <pre><code>$contacts = Contact::whereUserId(Auth::id())
                  -&gt;select('id', 'first_name', 'last_name', 'email', 'age')
                  -&gt;get();
  
  return response()-&gt;json($contacts);
  </code></pre>
  
  <p>I want to escape those name fields for html/script injection before rendering them in a DataTable, such as first and last names.  The only way I can think to do it is to loop through each row in the collection, and for each, loop through each field, and if it's a string, use <code>e()</code> on it.</p>
  
  <p>Is there something in the Laravel framework to handle this process?  Or a good package?  I'd rather not do it every time <code>toJson()</code> runs, since there may be times I don't want to run that, or like if it's an API call and I need to return the raw json data.</p>
  
  <p>Any advice?  I'm currently on Laravel 5.2.</p>
  
  <p>For the record, only a few of my fields are meant to contain html.</p>
  
  <p>UPDATE: As pointed out in the comments, I am using DataTables.  Currently, I use the <code>render</code> option, which is just a closure, on each column I want to escape and use a javascript-based strip tags/html entities function.  I kind of felt like I was doing it wrong, that there should be some function to do this automatically in the Laravel framework given how common it is plus the way blade templates are set up, but is this considered an ideal solution then?</p>