I have been developing a web app which collects data from database and print. I am using the Laravel framework. I have shown below the code use. I can display the JSON response directly in the my PHP code, but if I try to iterate through the JSON response I cannot get anything.
Here is how I generate the JSON object using Laravel Facades library:
$worklogs = Response::json($data, $this->getStatusCode(), $headers);
Here is the code I used to pass the data to the PHP page:
return view('index')->with('worklogs', $worklogs);
I can print the collected data from the PHP page using the following code:
{{ $worklogs }}
But if I try to iterate through it using the foreach
loop, an error occurs as shown:
In the PHP page this is how I coded it, but it is not working:
First and foremost as Bogdan Bocioaca said in his answer you only use the Response::json
function when you want to return Json only(mostly for APIs so that other apps can access your json data). For example the code below would return JSON which might be read by a mobile app
$worklogs = WorkLog::all();
return Response::json([
'worklogs' => $worklogs
], $headers);
By my understanding of your question you want to pass the data directly to the view, so your code should ideally be as follows:
$worklogs = WorkLog::all();
return view('index',compact('worklogs'));
(Note that above i chose to use the compact()
instead of with->()
because its cleaner)
Then you can iterate over your code in the as you wanted:
@foreach($worklogs as $worklog)
<td>{{$worklog->id}}</td>
<td>{{$worklog->name}}</td>
<td>{{$worklog->company}}</td>
@endforeach