2017-08-17 118 views
0

我想通過Laravel中的嵌套對象進行循環並獲取刀片文件的值。在Laravel循環嵌套對象

樣本對象:

[ 
    { 
     "id": 43, 
     "user_id": 2, 
     "event": "updated", 
     "auditable_id": 34, 
     "auditable_type": "App\\Bill", 
     "old_values": { 
      "message": "test messgare", 
      "napprover": "24", 
      "status": "Added" 
     }, 
     "new_values": { 
      "message": "Second Audit", 
      "napprover": "10001", 
      "status": "Bill Processing" 
     }, 
     "url": "http://localhost:8000/admin/bills/34", 
     "ip_address": "127.0.0.1", 
     "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3186.0 Safari/537.36", 
     "created_at": "2017-08-16 18:44:12" 
    }, 
    { 
     "id": 41, 
     "user_id": 2, 
     "event": "created", 
     "auditable_id": 34, 
     "auditable_type": "App\\Bill", 
     "old_values": [], 
     "new_values": { 
      "bill_no": "2017081527", 
      "bill_type": "BILL", 
      "bill_date": "08/15/2017", 
      "vendor_id": "2563582", 
      "priority": "Moderate Priority", 
      "amount": "125245", 
      "message": "test messgare", 
      "initiator": "10001", 
      "napprover": "10003", 
      "tat": "1", 
      "status": "Added", 
      "department": "6", 
      "created_at": "2017-08-15 11:57:45" 
     }, 
     "url": "http://localhost:8000/admin/bills", 
     "ip_address": "127.0.0.1", 
     "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3185.0 Safari/537.36", 
     "created_at": "2017-08-15 11:57:45" 
    } 
] 

控制器:

public function show($id) 
{ 
    $bill = Bill::findOrFail($id); 
    $vendor = $bill->vendor_id; 
    $user = User::where('vendor_id', $vendor)->get(); 
    $all = $bill->audits()->get(); 
    return view('admin.BillDetail', compact('bill','user','all')); 
} 

刀片文件:

@foreach($all as $al) 
    @foreach($all as $a) 
    <li>{{$a}}</li> 
    @endforeach 
@endforeach 

我想訪問old_values & new_values對象

如何循環

回答

1

得到這些值當我看到你的對象樣本old_values & new_values是單一的對象不是對象的數組,這樣你就可以做到這一點如下:

@foreach($all as $al) 
    @if(isset($al->new_values)) 
    <li>{{$al->new_values->message}}</li> 
    @endif 
@endforeach 

注意:如果存在null或空對象的可能性,那麼在訪問對象的任何屬性之前,您需要添加一些檢查,否則它會通過異常。

+0

謝謝,但沒有奏效收到此錯誤 http://prntscr.com/g9xfmw –

+0

已經告訴你,你需要檢查存在陣列存在的值或不否則它會通過一個例外。 –

+0

我編輯了答案嘗試類似的東西。 –