Trying to get property 'title' of non-object

Posted 3 weeks ago by ufodisko

Following: https://laracasts.com/series/lets-build-a-forum-with-laravel

I'm getting Trying to get property 'title' of non-object whenever I try to access $activity->subject->thread->title

It works with Jeff in the tutorial but not with me.

This is ProfilesController

public function show(User $user, Reply $reply, Favorite $favorite)
    {
        $activities = $user->activity()->latest()->with('subject')->get();

        //return $activities;

        return view('profiles.show', [
            'profileUser' => $user,
            'activities' => $activities
        ]);
    }

return $activities returns the following results

[{
id: 12,
user_id: 101,
subject_id: 10,
subject_type: "App\Thread",
type: "created_thread",
created_at: "2019-06-24 10:16:53",
updated_at: "2019-06-24 10:16:53",
subject: {
    id: 10,
    user_id: 101,
    channel_id: 6,
    title: "Metallica rules!",
    body: "hell yea",
    created_at: "2019-06-24 10:16:53",
    updated_at: "2019-06-24 10:16:53",
    replies_count: 0,
owner: {
    id: 101,
    name: "James",
    email: "[email protected]",
    email_verified_at: null,
    created_at: "2019-06-23 20:13:22",
    updated_at: "2019-06-23 20:13:22"
},
channel: {
    id: 6,
    name: "repellendus",
    slug: "repellendus",
    created_at: "2019-06-23 20:11:37",
    updated_at: "2019-06-23 20:11:37"
 }
}
}]

I don't see thread nested array from which Jeff is pulling the title

I don't really understand what's going wrong.

User model

public function activity()
    {
        return $this->hasMany(Activity::class);
    }

Reply Model

public function thread()
    {
        return $this->belongsTo(Thread::class);
    }

Activity model

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

The view profiles/show.blade.php

@foreach($activities as $activity)
         @isset($activity->subject)
                @include("profiles.activities.{$activity->type}")
        @endisset
@endforeach

And finally profiles/activities/created_thread.blade.php

<h6 class="tt-title">
            <a href="/threads/{{ $activity->subject->channel->slug }}/{{ $activity->subject->thread_id }}"
               class="font-weight-bold">
                {{ $activity->subject->thread->title }} <!-- ERROR HERE -->
            </a>
        </h6>

Thank you.

Please sign in or create an account to participate in this conversation.