skip to Main Content

I was trying to print API response data as collection on blade for that i have used following line

$customers =   collect(json_decode($response, true));

But whenever i tried to print with following code:

 @foreach($customers as $row)
    <tr>
      <td>{{$row->first_name}} {{$row->last_name}}</td>
      <td>{{$row->email}}</td>
      <td>{{$row->phone}}</td>
      <td>{{$row->addresses['country_name']}}</td>
    </tr>
  @endforeach 

it shows bellow error, What’s the problem here?

Attempt to read property "first_name" on array

Here is the API response:

IlluminateSupportCollection {#341 ▼ // appHttpControllersIntegrationController.php:61
  #items: array:1 [▼
    "customers" => array:3 [▼
      0 => array:27 [▼
        "id" => 6895839936762
        "email" => "[email protected]"
        "accepts_marketing" => false
        "created_at" => "2023-10-20T11:06:26-04:00"
        "updated_at" => "2023-10-20T11:06:26-04:00"
        "first_name" => "Russell"
        "last_name" => "Winfield"
        "orders_count" => 0
        "state" => "disabled"
        "total_spent" => "0.00"
        "last_order_id" => null
        "note" => "This customer is created with most available fields"
        "verified_email" => true
        "multipass_identifier" => null
        "tax_exempt" => false
        "tags" => "VIP"
        "last_order_name" => null
        "currency" => "USD"
        "phone" => "+16135550135"
        "addresses" => array:1 [▶]
        "accepts_marketing_updated_at" => "2023-10-20T11:06:26-04:00"
        "marketing_opt_in_level" => null
        "tax_exemptions" => []
        "email_marketing_consent" => array:3 [▶]
        "sms_marketing_consent" => array:4 [▶]
        "admin_graphql_api_id" => "gid://shopify/Customer/6895839936762"
        "default_address" => array:17 [▶]
      ]
      1 => array:26 [▶]
      2 => array:26 [▶]
    ]
  ]
  #escapeWhenCastingToString: false
}

2

Answers


  1. In your case, I think the correct foreach that you want is:

    @foreach($customers[0]->customers as $row)
        <tr>
          <td>{{$row->first_name}} {{$row->last_name}}</td>
          <td>{{$row->email}}</td>
          <td>{{$row->phone}}</td>
          <td>{{$row->addresses['country_name']}}</td>
        </tr>
    @endforeach
    
    Login or Signup to reply.
  2. In reality, $row is an associative array, but you are using it like an object. Instead of using object notation to access its elements, you should use array notation. Change your code as follows:

    @foreach($customers['customers'] as $row)
        <tr>
          <td>{{$row['first_name']}} {{$row['last_name']}}</td>
          <td>{{$row['email']}}</td>
          <td>{{$row['phone']}}</td>
          <td>{{$row['addresses']['country_name']}}</td>
        </tr>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search