简体   繁体   English

如何在 laravel 刀片视图中显示 JSON 数据

[英]How to display JSON data in laravel blade view

I am getting a JSON response我收到 JSON 响应

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

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

the response is not structured like this I have made is readable for now响应的结构不像我所做的那样现在是可读的

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"
  ]
}

Controller Controller

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

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

what I wish is to display host and abcd-io.test separately我希望分别显示hostabcd-io.test

I tried using {{ $log->general['host'] }} but it didn't worked我尝试使用{{ $log->general['host'] }}但没有奏效

Assuming "general" is a string, you might have to use json_decode($json) to convert a JSON string to an array and do something like this:假设“general”是一个字符串,您可能必须使用 json_decode($json) 将 JSON 字符串转换为数组并执行以下操作:

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

Retrieve host检索主机

$json['host']

The solution is to and cast for the column in the model.解决方案是对 model 中的列进行强制转换。

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

and hence in the view I can show it as因此在视图中我可以将其显示为

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM