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

cupcakedream's avatar

Can't Get Attribute Of Related Model

Hey All - I'm running Laravel 6.2 and am getting an error trying to get any attribute of a model through a "belongsTo" relationship. I'm using a "hasmanythrough" relationship to get activities from a user model - maybe that has something to do with it?

Also I noticed if I dump and die dd($activity->contact()) I can see the contact model but when I try dd($activity->contact()->id) it will fail. Very perplexing!

Controller:

    public function index() {
        $user = Auth::user();
        $activities = $user->activities();
        return view( 'activity.index', [ 'activities' => $activities ] );
    }

Activity Model

    public function contact() {
        return $this->belongsTo( 'App\Contact' )->first();
    }

Blade template

@if ( $activities->count() )
    @foreach ( $activities as $activity )
        <div class="contact route" data-url="/outreach/list?q={{ $activity->id }}">
            @php dump($activity->contact()->id) @endphp
        </div>
    @endforeach
@endif
0 likes
10 replies
Sinnbeck's avatar

If you have () you point to the method not the relation. It should be

dd($activity->contact->id)
cupcakedream's avatar

That's good to know - thanks for the heads up. I remove ->first() from the relationship and tried dump($activity->contact->id) but still getting an error Trying to get property 'id' of non-object.

Sinnbeck's avatar

Well the same issue here it seems

$user = Auth::user();
        $activities = $user->activities;
cupcakedream's avatar

Unfortunately still not working - I've removed the User model all together and am just using $activities = \App\Activity::get() but still have the same problem.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Also be sure that all activities have a contact

Or do

$activity->contact->id ?? ''
Sinnbeck's avatar

Just noticed. This is also wrong. It should not have first

public function contact() {
        return $this->belongsTo( 'App\Contact' );
    }
cupcakedream's avatar

Ah! That was it! I accidentally seeded my DB with some user_id values set at 0 facepalm. Thanks so much for troubleshooting this with me - I super appreciate it!

Sinnbeck's avatar

Happy to help. Last point. Make sure to eagerload your relations

$activities = \App\Activity::with('contact')->get()
Sinnbeck's avatar

Exactly. It populates the data from the start.

Without it, laravel queries the data (from the database) for each record one at the time

You can Google "laravel n+1"

Please or to participate in this conversation.