Al78
Al78

Reputation: 41

eloquent - accessing the property of parent model in shared one to many relationships

I have the following eloquent models:

[User]

public function studentProfile()
{
        return $this->hasOne('App\StudentProfile');
}

public function tutorProfile()
{
        return $this->hasOne('App\TutorProfile');
}

[StudentProfile]

public function user()
{
        return $this->belongsTo('App\User');
}

public function tutorialLogs()
{
        return $this->hasMany('App\TutorialLog', 'student_profile_id');
}

[TutorProfile]

public function user()
 {
        return $this->belongsTo('App\User');
 }

 public function tutorialLogs()
 {
        return $this->hasMany('App\TutorialLog', 'tutor_profile_id');
 }

[TutorialLog]

public function tutorProfile()
{
        return $this->belongsTo('App\TutorProfile');
}

public function studentProfile()
{
        return $this->belongsTo('App\StudentProfile');
}

My database structure also is like this:

[users]

id
fname

[student_profiles]

id
notes
user_id

[tutor_profiles]

id
speciality
user_id

[tutorial_logs]

id
notes
student_profile_id
tutor_profile_id

I am trying to get the tutorial logs for a tutor based on the tutor_profile_id. I have done that, however when I am going to get the tutor name or student name I can’t.

Here is my code:

$tutor = User::whereId(Auth::user()->id)->first();

// get the tutorial logs
$tutorial_logs = $tutor->tutorProfile->tutorialLogs()->orderBy('date')->get();

I don’t know how to access the student fname or tutor fname in the view.

Any help? thanks

Upvotes: 1

Views: 2056

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

The student fname you can access:

{{ $tutor->student_profile->user->fname }}

The tutor fname you can access

{{ $tutor->user->fname }}

Upvotes: 2

Related Questions