livreson ltc
livreson ltc

Reputation: 733

Laravel: How to access Object inside an array

I trying to return access the attributes inside a array of object and it is giving this error Exception: Property [id] does not exist on this collection instance.

Here is what I have tried:

protected function formatted($classroom)
{
  return [
    'courses' => [
      'id' => $classroom->courses->id,
      'name' => $classroom->courses->name,
      'slug' => $classroom->courses->slug,           
      'coursteachers' => [
          'id' => '$classroom->courses->coursteachers->id',
          'email' => '$classroom->courses->coursteachers->email',
          'uid' => '$classroom->courses->coursteachers->uid',
       ]
    ],
  ];
}

And here is the actual data:

    "courses": [
    {
        "id": 1,
        "name": "Analytics",
        "slug": "analytics",
        "status_id": 1,
        "deleted_at": null,
        "pivot": {
            "classroom_id": 2,
            "courses_id": 1
        },
        "coursteachers": [
            {
                "id": 3,
                "uid": "S0120-46890",
                "email": "[email protected]",
                "user_type": "Teacher",
           }]
      }]

Upvotes: 1

Views: 4891

Answers (2)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

You need to iterate through courses and also courseteachers since they both represent an array but rather an object

protected function formatted($classroom)
{
  $result = [];
  foreach($classroom->courses as $course) {
   $result[] = [
    'courses' => [
      'id' => $classroom->courses->id,
      'name' => $classroom->courses->name,
      'slug' => $classroom->courses->slug,           
      'coursteachers' => $this->getCourseTeachers($cours)
    ],
   ];
  }
  return $result;
}
private function getClassroomTeachers($classroom) {
 $result = [];
 foreach($classroom->courses as $cours)
 {
    foreach ($cours->coursteachers as $key => $teacher) {
      $result[] = [
        // 'coursteachers'=> [
          'id' => $teacher->id,
          'email' => $teacher->email,
          'uid' => $teacher->uid,
          'last_name' => $teacher->profile->last_name,
          'first_name' => $teacher->profile->first_name,
          'middle_name' => $teacher->profile->middle_name,
        // ],
      ];
    }
 }
 return $result;
}

Upvotes: 1

Parakrama Dharmapala
Parakrama Dharmapala

Reputation: 1229

Since courses is an array, you should pick an object using the proper index. Foe example: try $classroom->courses[0]->id instead of $classroom->courses->id. Here, '0' is the index.

Also it is better if you check if the index exists before you do it. For an example.

'id' : isset($classroom->courses[$index]) ? $classroom->courses[$index]->id : ''

Edit:

In case of a Eloquent collection you should use $classroom->courses->get($index)->id instead of array like retrieval.

Upvotes: 0

Related Questions