Laravel array to json format
You could return an json_encoded array from the controller like so:
public function index()
{
$posts = Post::all();
$json = json_encode($posts);
return View::make('posts.index', compact('posts', 'json'));
}
Which you then can work on in your view like you'd like:
<script type="text/javascript">
var data = {{ $json }};
console.log(data);
</script>
Also, if you have sensitive fields on your post model, you should exclude these in the model class to prevent them to show in your javascript inspector:
class Post extends \Eloquent {
...
protected $hidden = array(
'id',
'created_at',
'updated_at'
);
...
}
Use Eloquents built in function toJson
to get your rows as json.
<script type="text/javascript">
var data = "{{ $posts->toJson() }}";
console.log(data);
</script>
If there's some fields you don't want to include, add the field to the hidden
property in your model as Jimmy mentioned.
If you looking for "high-level" way to convert plain array to json, you can use laravel collections.
collect(['a' => 1, 'b' => 2, 'c' => 3])->toJson();