wisnuaryadipa
wisnuaryadipa

Reputation: 760

Difference between $object->attribute and $object['attribute'] in Laravel

I'm developing with DataTables in Laravel and trying to make an object manually using collect() to create a collection. When I push the collection into the DataTable, there is something wrong, and I can't call my object with this $object->attribute.

After I get the error with that, I already tried to call an attribute with $object['attribute'], and it works well.

Can someone give me insight about the differences and how I can convert $object['attribute'] into $object->attribute?

This is my query to create object

$result = collect();
$item = collect([
         'row' => ($key+1),
         'item_id' => $value->uid,
         'item' => $value->nama_item,
         'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
         'kategori' => $value->jenis_item->jenis_item,
         'gudang_id' => $id_gudang
]);
$result->push($item);

Upvotes: 0

Views: 522

Answers (3)

user3785966
user3785966

Reputation: 2980

You can try the following way,

   $result = collect();
    $item = collect([
        'row' => ($key+1),
        'item_id' => $value->uid,
        'item' => $value->nama_item,
        'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
        'kategori' => $value->jenis_item->jenis_item,
        'gudang_id' => $id_gudang
     ]
    );
    $result->push($item);

    $resultObj = json_decode($result);

    foreach($resultObj as $obj){
        echo $obj->row;
    }

Upvotes: 0

Namoshek
Namoshek

Reputation: 6544

DataTables calls internally toArray() on the collection items when you build the table. This happens during transformation of the data. It will also flatten nested objects (e.g. loaded Eloquent relations in case of an EloquentDataTable) into an array with depth 1 (per row of the table).

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

Accessing $object['attribute'] means $object is an array and accessing $object->attribute means $object is an object.

To convert array to object:

$object = (object) $object;

Additionally, to convert object to array:

$object = (array) $object;

Upvotes: 2

Related Questions