admin管理员组文章数量:1180440
So I'm trying to convert a Laravel array into json
so I can then manipulate it through javascript. Im not sure how this is achieved correctly. Here is the code, so far
@foreach ($posts as $post)
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-8 tag">
<h4><strong><a href="{{{ $post>postName }}}">#{{String::title($posts->postName) }}</a></strong></h4>
</div>
</div>
<!-- ./ post title -->
</div>
</div>
<hr />
@endforeach
<script type="text/javascript">
var data = "{{ ($posts) }}"; // ??
console.log(data);
</script>
So I'm trying to convert a Laravel array into json
so I can then manipulate it through javascript. Im not sure how this is achieved correctly. Here is the code, so far
@foreach ($posts as $post)
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-8 tag">
<h4><strong><a href="{{{ $post>postName }}}">#{{String::title($posts->postName) }}</a></strong></h4>
</div>
</div>
<!-- ./ post title -->
</div>
</div>
<hr />
@endforeach
<script type="text/javascript">
var data = "{{ ($posts) }}"; // ??
console.log(data);
</script>
Share
Improve this question
asked Feb 15, 2015 at 8:19
MrSSS16MrSSS16
4733 gold badges8 silver badges22 bronze badges
5 Answers
Reset to default 12You 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'
);
...
}
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();
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.
<script type="text/javascript">
let data = @json($posts);
console.log(data);
</script>
you don't need to do all that, just use the php inbuilt function json_encode
$json = json_encode($posts);
echo $json;
<script type="text/javascript">
var data = "$json"; // ??
console.log(data);
</script>
本文标签: javascriptLaravel array to json formatStack Overflow
版权声明:本文标题:javascript - Laravel array to json format - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738110352a2064515.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论