oliverbj
oliverbj

Reputation: 6052

Laravel - Trying to get property of non-object - PHP

I am currently trying to learn Laravel and PHP in general.

I need to be able to import an Excel file, then get the data from that file. Currently, the import part works and I can see the data from the file. However, I am having trouble accessing the data.

I've read about the toArray() function in Laravel, and is using that as below:

 $data = Excel::load($path, function($reader) {})->skipColumns(2)->get();
 $data = $data->toArray();

         foreach ($data as $key => $value) {

           //We only need some of the available data.
           echo $value->next_milestone_desc_cur._comp._incl_rltd;
           echo $value->shipment_id;

          }

Above code gives me below error:

Trying to get property 'next_milestone_desc_cur' of non-object

Below is an output from the array, which I have generated using dd($value):

array:543 [▼
  0 => array:20 [▼
    "next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
    "milestone_cur._comp._sequence_no" => "005"
    "cur._comp._export_validation" => "NOT OK"
    "shipment_id" => "SBRY0162091"
    "consol_id" => "CDK327188"  ]
  1 => array:20 [▼
    "next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
    "milestone_cur._comp._sequence_no" => "005"
    "cur._comp._export_validation" => "NOT OK"
    "shipment_id" => "SBRY0162124"
    "consol_id" => "CDK327221"
  ]

What am I doing wrong here? I have also tried echo $value[0]->next_milestone_desc_cur._comp._incl_rltd;, however this doesn't work either.

Upvotes: 2

Views: 1727

Answers (2)

Script47
Script47

Reputation: 14530

You are trying to access an array as an object hence your error and to address you second point, you need to use a nested loop to then access the sub-array.

Your array looks something like this:

$array = [
  0 => [
    0 => [
      'test' => 'value'
    ],

    1 => [
      'test' => 'something'
    ]  
  ],

  1 => [
    0 => [
      'test' => 'value'
    ],

    1 => [
      'test' => 'something'
    ]  
  ]  
];

You need the following loop:

foreach ($array as $key => $nested) {
  foreach ($nested as $nested_value) {
    // You have access to your inner arrays.
    echo  $nested_value['test'] . ' | ';
  }
}

Where your nested loops $nested would be $value.

Live Example

Repl

Upvotes: 2

Karol Samborski
Karol Samborski

Reputation: 2955

Your output from dd($value) shows that $value is an array. So you cannot use arrow notation that is for objects. Change these lines:

echo $value->next_milestone_desc_cur._comp._incl_rltd;
echo $value->shipment_id;

To:

echo $value[0]["next_milestone_desc_cur._comp._incl_rltd"];
echo $value[0]["shipment_id"];

Upvotes: 0

Related Questions