dongre9937 2016-05-30 18:34
浏览 92
已采纳

使用Laravel框架在PHP中打印JSON响应

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

  • 写回答

2条回答 默认 最新

  • duanqun9618 2016-05-31 02:57
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?