I recently experimented with Laravel 4, which so far has been a joy to use. However, I am experiencing a problem, not with Laravel 4, but rather my own insecurities.
I have a database containing 3 rows with 4 columns. For example, let's say that the columns are:
content_id, Content Type, content_data, timestamp
The column 'content_data' contains a JSON encoded array of approximately four key pairs.
When I retrieve these rows from the database (using Eloquent) and pass the data into my view, how can I also parse JSON in my click template?
After searching and accessing the Laravel documentation, my thought is that you cannot, so I tried to decode the JSON back into an array inside my controller, and then pass it to my view.
So far I have tried the following in my class:
<?php
class PageController extends \BaseController {
public function index()
{
$data = Content::
->where('content_type', 1)
->get();
foreach($data as $content)
{
$items[] = json_decode($content->content_data);
}
return View::make('pages.page2')
->with('data', $data)
->with('items', $items);
}
}
However, in my Blade template, when I run the foreach loop to loop through the selected lines, I tried to run another foreach loop in the first one, which iterates over the $ items array to retrieve their values, but since it is a loop in the loop, I get duplicate json values.
My clip template looks like this:
@extends('layouts.pages');
@section('content_body')
<h1>My <span>title</span></h1>
<div class="column col-1">
<ul>
{{-- loop through the database rows --}}
@foreach($data as $row)
{{-- loop through the json decoded values --}}
@foreach($items as $item)
{{ $item['title'] }}
@endforeach
@endforeach
</ul>
</div>
@stop
Not sure if I explained this correctly, but basically I just want to be able to parse my encoded json array in a loop that displays the extracted db lines
I hope this makes sense to anyone who can help.