Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fuzzyduck's avatar

Eager Loaded MorphTo through Relationship - Trying to get property non object


class Quiz extends Model {

    public function answers() {
        return $this->hasMany( 'App\Question', 'quiz_id', 'id');
    }

}

class Question extends Model {
    
    public function quiz() {
        return $this->belongsTo( 'App\Quiz' );
    }

    public function word_cloud() {
        return $this->morphOne( 'App\WordCloud', 'word_cloudable');
    }

}

class WordCloud extends Model {

    public function word_cloudable()
    {
        return $this->morphTo();
    }

}

I am primarily loading the Quiz model using eager loading to include the Question and the WordCloud.

$quiz = $quizModel->with('questions')->with('questions.word_cloud')->find(1)

I have no issue with accessing the questions within the blade template in a foreach loop.

@foreach($quiz as $q)

    @foreach($q->answer as $answer)
        
        {{ $answer->value }}

    @endforeach

@endforeach

But If I then try to output the answer MorphOne relationship of word_cloud {{ $answer->word_cloud->image }} I get an exception Trying to get property 'image' of non-object.

However, if I dd( $answer->word_cloud->image ) I get a string for the value that I am looking for "my-image-name.jpg".

If I dd( $answer->word_cloud ) it outputs a model object App\WordCloud but not a collection.

Is there something that I am missing with this?

0 likes
3 replies
fuzzyduck's avatar

Have you ever had a problem where you stare at it going WTF? Only to have your silly mistake's answer come to you while not thinking about the problem?

Well this issue is solved.

The relationship worked fine. The problem is that the relation didn't exist for all $answer elements. So when the loop finally go to one where it didn't exist it would throw an error.

So checking if the $answer->word_cloud solved the issue for me.

Sinnbeck's avatar
public function answers() {
        return $this->hasMany( 'App\Qustion', 'quiz_id', 'id');
    }

Shouldn't that be Question not Qustion

fuzzyduck's avatar

Yes it should have been, typo on my part when extracting code into the form post.

Please or to participate in this conversation.