Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel array to json format

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>
like image 686
MrSSS16 Avatar asked Feb 15 '15 08:02

MrSSS16


1 Answers

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'
    );

    ...
}
like image 146
Jimmy Bernljung Avatar answered Sep 30 '22 20:09

Jimmy Bernljung