Maulik Bhatt
Maulik Bhatt

Reputation: 33

Laravel access values from object in object

In one of the controller function

$readings = Reading::orderBy('reading_date_time', 'DESC')->get();
dd($readings);

This gives

Illuminate\Database\Eloquent\Collection {#1883
  #items: array:160 [
    0 => App\Reading {#1722
      #fillable: array:6 [ …6]
      #connection: "mysql"
      #table: "readings"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [ …8]
      #original: array:8 [ …8]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [ …1]
    }...

How can I access the actual values of readings table. And use them for operations like array_column().

Upvotes: 0

Views: 688

Answers (2)

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

You may use toArray() helper

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$readings = Reading::orderBy('reading_date_time', 'DESC')->get()->toArray();

/*
    [
        ['column1' => 'value1', 'column2' => 'value2', ...],
        ['column1' => 'value1', 'column2' => 'value2', ...],
        ['column1' => 'value1', 'column2' => 'value2', ...],
        ...
    ]
*/

Then you may use array_column() on $readings array

$pluckedValues = array_column($readings, 'chosen_column');

print_r($pluckedValues);

Upvotes: 0

TsaiKoga
TsaiKoga

Reputation: 13394

This function already give you the result, and the result is collection.

You can call the attribute by single object in collection:

$readings->first()->reading_date_time;

and you can use method-pluck to get the attribute values from collection, it just like array_column:

$readings->pluck('reading_date_time');

If you use array_column, you can use method-toArray to change collection to array:

array_column($readings->toArray(), 'reading_date_time')

Upvotes: 1

Related Questions