alexthedev's avatar

Can't access user_id through BelongsTo Relationship

Hi, I have two models Logbook and LogItem. Logbook belongs to user and Logitem belongs to Logbook. What I'm trying todo is access the user_id of the Logitem through the Logbook relationship. When I try i get: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$user_id

$Logitem->Logbook()->user_id;

Here is the ralationships for the Logbook

//Logbook
 public function Logitems(): HasMany
    {
        return $this->hasMany(Logitem::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

and here's Logitem

 public function Logbook(): BelongsTo
    {
        return $this->belongsTo(Logbook::class,);
    }

I can dd() Logbook and see the user_id and I can dd() $Logitem->Logbook() and see the parent Logbook.

0 likes
1 reply
aknEvrnky's avatar

You need to call the magic property, which is

$Logitem->Logbook->user_id;

Please or to participate in this conversation.