2016-05-30 18:34



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:

error captured

In the PHP page this is how I coded it, but it is not working: captured index.blade.php file portion

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanqun9618 duanqun9618 5年前

    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)
    点赞 评论 复制链接分享
  • dqwh1219 dqwh1219 5年前

    I'm not sure I understand .. first of all this is how you return a json:

    return Response::json([
        'hello' => $value
    ], $headers);

    Second: what do you mean iterate the jSon? Third: your error messages state that Undefined variable $datas .. not $data, $datas. are you sending the $data param to the view?

    点赞 评论 复制链接分享