Monday, April 3, 2017

Laravel - foreach loop returns Trying to get property of non-object

I have a collection of arrays (18), that ALL have a relation - question.

Function getting the data:

 $auditResults = Audit::where('audit_id', $id)
     ->with('question', 'question.auditQuestion')
     ->get();

Within the question array, I can see the attributes I'd like to access. When I attempt to access it, I get a Trying to get property of non-object

Collection:

Collection {#407 ▼
  #items: array:18 [▼
    0 => Audit {#411 ▶}
    1 => Audit {#412 ▶}
    2 => Audit {#413 ▶}
    ... shortened for brevity's sake
    14 => Audit {#425 ▶}
    15 => Audit {#426 ▶}
    16 => Audit {#427 ▶}
    17 => Audit {#428 ▶}
  ]
}

Output of anAudit:

@foreach($auditResults as $answer)
    
@endforeach


{  
       "id":1,
       "audit_id":1,
       "audit_questions_details_id":2,
       "question":{  
          "id":2,
          "audit_question_id":2,
          "question_number":1,
          "comment":1,
          "header":0,
          "created_at":"2017-03-27 12:16:50",
          "updated_at":"2017-03-27 12:16:50",
          "audit_question":{  
             "id":2,
             "audit_detail_id":1,
             "question":"Lorum Ipsum Dorum",
             "created_at":"2017-03-27 12:16:50",
             "updated_at":"2017-03-27 12:16:50"
          }
       },
       "score":null,
       "comment":null,
       "created_at":null,
       "updated_at":null
    }

If I then proceed to access the question relationship:

@foreach($auditResults as $answer)
    
@endforeach

It outputs only a number (I'm unsure what it actually is!, as I'd expect it to output the question relationship):

1
2
3
4

Why is this only outputting a number, when it should be outputting the question array itself, as shown above?

The error is shown when I try to access the question relation:

@foreach($auditResults as $answer)
    
@endforeach

Audit Model:

class Audit extends Model
{
    protected $fillable = [
        'audit_id', 'audit_questions_details_id', 'question', 'score', 'comment'
    ];

    public function auditScore()
    {
        return $this->belongsTo('App\AuditScore', 'id', 'audit_id');
    }

    public function question(){
        return $this->belongsTo(AuditQuestionDetail::class, 'audit_questions_details_id');
    }

}

Data of Audit Model:

AuditModelData

AuditQuestionDetail Model:

class AuditQuestionDetail extends Model
{
    protected $table = 'audit_questions_details';

    protected $fillable = [
        'audit_question', 'question_number', 'comment',
    ];

    public function auditQuestion()
    {
        return $this->hasOne(AuditQuestion::class, 'id', 'audit_question_id');
    }

    public function score()
    {
        return $this->hasMany(Audit::class);
    }
}

AuditQuestionDetails Data

Many thanks.



via Ben

Advertisement