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

Dandefer's avatar

Problem with my relation table

Hello,

I'm a beginner in Laravel, can you help me please ?

I create app from older app and I recovers existing tables.

I have 2 table (Member and Student), a student can be only a member and vice versa . In members I have the student_id.

I have already a relation in member (belongsTo Student) for another needs.

My problem, is I want to get a value (bam_id who is in Member table) from a student model. So I make a relation in Student model (belongsTo Member)

And I try $students->member()->bam_adherent but I get this error message : "Trying to get property 'bam_adherent' of non-object"

$students is a Student model

I don't understant how I can get the value

Do you have an idea of my error ?

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

If the foreign key is on the other table, it is a hasX relation; in this case, it is a hasOne:

// Student
public function member()
{
	return $this->hasOne(Member::class);
}

Also, use the property member to get the property, because the method returns a (HasOne) Builder instance

$students->member->bam_adherent
bobbybouwmann's avatar

You should try $students->member->bam_adherent

->member() returns the query builder for the members table ->member returns the member model that belongs to the student.

Note that if member doesn't exist the above code will fail because $member is null

Dandefer's avatar

Okk ! It's work with a HasOne relation. Thanks you for your help.

Obviously, I have diffcults with relationships

Please or to participate in this conversation.