Laravel刀片迭代php数组/对象

I'm having trouble outputting a list of key value pairs in Laravel blade.

My show.blade.php template is:

@extends('layouts.app')

@section('content')

  <ul>
    @foreach ($datapoint as $key => $value)

      <li>{{ $key, $value }}</li>

    @endforeach
  </ul>

  {{ $datapoint }}
@endsection

And my controller which displays this template is:

<?php

namespace App\Http\Controllers;

use App\Hyfes;

use Illuminate\Http\Request;

class CaptainController extends Controller
{
    public function getLiveData ()
    {
      $datapoint = Hyfes::find(1);

      return view('captain.show')->with('datapoint', $datapoint);
    }
}

The data output to the view in the browser is this:

  • incrementing
  • exists
  • wasRecentlyCreated
  • timestamps

    {"date":"08/07/2017","time":"12:02:25","boat_name":"cyclone","current_location":"North Greenwich Pier","status":"docked","embarked":26,"disembarked":2,"people_on_board":24,"current_speed":0,"hotel_power":231,"battery_power_demand":342,"battery_output_power":23,"engine_output_power":12,"battery_power_stored":100,"battery_depth_of_discharge":323,"fuel_consumption_rate":7,"nox":432,"co2":213,"battery_state_of_charge":100,"id":1}

Ideally, I would like to see a list of bullet points showing e.g.:

  • date: 8/07/2017
  • time: 12:00:01
  • boat_name: cyclone

The function Hyfes::find(1) will return an object of the type App\Hyfes and not an array. By looping over the key value pairs you are getting all properties. Laravel adds a lot of extra properties for keeping track of the object.

A better way to do this is using the Laravel getAttributes function. This will only get the attributes loaded from the database. Like so:

@foreach ($datapoint->getAttributes() as $key => $value)
    <li>{{ $key }}: {{ $value }}</li>
@endforeach

You are trying to iterate over a non array variable in your template. You have to be explicit about the values of the objects you would like to see in your template.

@extends('layouts.app')

@section('content')

  <ul>
      <li>date: {{ $datapoint->date }}</li>
      <li>time: {{ $datapoint->time }}</li>
      <!-- and so on -->
  </ul>

@endsection