猿问

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

我收到 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'));

}

我希望分别显示host和abcd-io.test


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


冉冉说
浏览 141回答 2
2回答

哔哔one

假设“general”是一个字符串,您可能必须使用 json_decode($json) 将 JSON 字符串转换为数组,并执行如下操作://Convert&nbsp;JSON&nbsp;to&nbsp;array $json&nbsp;=&nbsp;json_decode($log->general,&nbsp;true);检索主机$json['host']

皈依舞

解决方案是对模型中的列进行铸造。protected $casts = [    'general' => 'array'];因此在视图中我可以将其显示为@foreach($logs as $log)  <div class="modal-body">    {{ $log->general['host'] ?? 'No host' }}  </div>@endforeach
随时随地看视频慕课网APP
我要回答