Home > Back-end >  how to access specific data or fields
how to access specific data or fields

Time:07-18

This is my function to display the data

public function settings(){
      $accounts = ScrapingTarget::with('accounts')
        //  ->distinct()
        ->where('accounts.group_id',333)
        ->get();
}

In my srapingTargetModel

public function accounts(){
    return $this->hasMany(Accounts::class, 'id', 'account_id');
}

**This is the display data but I want to access group id how to access group_id in accounts object **

[
  {
     "id": 1,
     "account_id": 1,
     "accounts": [
       "group_id": 333,
     ]
  }
]

CodePudding user response:

Use foreach Loop to access single data from the collection.

    foreach($accounts as $acount){
         $account->account_id;  // it will display account_id
         foreach($account->accounts as $relation_account){    // use foreach loop because of has Many relation
              $relation_account->group_id;    // it will display group_id 333
         }
    }

CodePudding user response:

There is a syntax error,

 $array = [
      {
         "id": 1,
         "account_id": 1,
         "accounts": [
           {"group_id": 333}
         ]
      }
    ]
    
return array[0]['accounts'][0];
  • Related