Home > Back-end >  Getting specific attribute value from Eloquent\Collection in Laravel
Getting specific attribute value from Eloquent\Collection in Laravel

Time:05-24

I am trying to get the attribute "date" value from the following returned data, how I can get it?

Illuminate\Database\Eloquent\Collection {#267 ▼
  #items: array:1 [▼
    0 => App\Models\Crisis_indicators_data {#255 ▼
      #table: "crisis_indicators_data"
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
       incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
       exists: true
       wasRecentlyCreated: false
      #attributes: array:4 [▼
        "c_i_data_id" => 1
        "date" => "2022-05-23"
        "indicator_id" => 30
        "value" => 11
      ]
      #original: array:4 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
       timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
}

I have tried the following ways, but no data returned

$row_data_temp->date
$row_data_temp[0]->date
$row_data_temp[0]['date']

I don't want to use for loop or foreach because performance-wise

CodePudding user response:

// get your main collection with all the attributes like this...

$users = Users::get();

// build your second collection with a subset of attributes. this new // collection will be a collection of plain arrays, not Users models.

$subset = $users->map(function ($user) {
    return $user->only(['id', 'name', 'email']);
});

stackoverflow ref:here

  • Related