【问题标题】:How to display JSON data in laravel blade view如何在 laravel 刀片视图中显示 JSON 数据
【发布时间】:2020-10-10 15:51:44
【问题描述】:

我收到 JSON 响应

@foreach($logs as $log)
  <div class="modal-body">
    {{ $log->general }}
  </div>

  <div class="modal-body">
    {{ $log->response_headers }}
  </div>
@endforeach

响应的结构不像我所做的那样现在是可读的

General
{
  "host": "abcd-io.test",
  "path": "api/v1/companies/hello.com",
  "request_ip": "127.0.0.1"
}

response_headers
{
  "X-Powered-By": [
    "Express"
  ],
  "Access-Control-Allow-Origin": [
    "*"
  ],
  "Content-Type": [
    "application/json; charset=utf-8"
  ],
  "Content-Length": [
    "4857"
  ],
  "ETag": [
    "W/\"12f9-UhKH0rSAm7BiHIeW5pbrH1gphXs\""
  ],
  "Date": [
    "Sat, 20 Jun 2020 12:51:28 GMT"
  ],
  "Connection": [
    "keep-alive"
  ]
}

控制器

public function index() {
   $logs = Log::where('user_id',auth()->user()->id)
          ->orderBy('created_at', 'DESC')->get();

   return view('api.logs', compact('logs'));
}

我希望分别显示hostabcd-io.test

我尝试使用{{ $log-&gt;general['host'] }},但没有成功

【问题讨论】:

  • 添加你的控制器代码
  • @TalhaF。用控制器更新了代码

标签: php json laravel laravel-blade


【解决方案1】:

解决方案是对模型中的列进行强制转换。

protected $casts = [
    'general' => 'array'
];

因此在视图中我可以将其显示为

@foreach($logs as $log)
  <div class="modal-body">
    {{ $log->general['host'] ?? 'No host' }}
  </div>
@endforeach

文档:https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting

【讨论】:

    【解决方案2】:

    假设“general”是一个字符串,您可能必须使用 json_decode($json) 将 JSON 字符串转换为数组并执行以下操作:

    //Convert JSON to array
    $json = json_decode($log->general, true);
    

    检索主机

    $json['host']
    

    【讨论】:

    • json_decode 给出错误“htmlspecialchars() 期望参数 1 为字符串,给定数组”
    猜你喜欢
    • 1970-01-01
    • 2023-01-08
    • 2017-09-04
    • 2019-02-22
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2021-02-14
    • 2020-05-08
    相关资源
    最近更新 更多