gerry
gerry

Reputation: 127

How to access nested json objects without json_decoding the collection

I have the following data structure:

[
   {
      "id": 1,
      "customer_id": "11",
      "customer_name": "Vic",
      "cheque_withdraw": {
         "id": 2,
         "request_date", "2019-03-30"
      }
   }
]

I have gotten this data from multiple tables through the following code;

$paginator = Cheque::with(['chequeWithdraw' => function($query){
        $query->where('withdraw_status' , 'withdrawn');
    }])
    ->paginate(5);

How do I access the nested json object request_date without having to convert my collection to an associative array? The reason why I do not want to convert the collection to an associative array is because I am having challenges paginating the data that has been json decoded. I am currently trying to access the request_date in my blade file this way;

@foreach($paginator as $cheque)
   {{ $cheque->cheque_withdraw->request_date }}
@endforeach

However, I am getting the following error;

Trying to get property 'request_date' of non-object

Upvotes: 3

Views: 860

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Actually you have chequeWithdraw and not cheque_withdraw

@foreach($paginator as $cheque)
   {{ $cheque->chequeWithdraw->request_date  ?? 'NA'}}
@endforeach

You might be trying to convert laravel collection to json or array. laravel convert camel case to snake case . So you were getting it for json not for laravel template.

Upvotes: 5

Related Questions