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);

3 Answers

2
MH2K9 On

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;
0
Namoshek On

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).

0
user3785966 On

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;
    }