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

amsm1992's avatar

Can't use property in Tinker even that the relations exists

I have 4 tables (users,teachers,courses,course_teacher)

so I have a foreign key in teachers table references id on users table, and course_teacher as pivot table (many to many relationship)

users table has (id,firstname,lastname,email,password) teachers table has (id,users_id,about) courses table has (id,name)

and I have these relations in the models:

// User.php
public function teacher() {
        return $this->hasMany(Teacher::class);
 }

// Teacher.php
public function course() {
        return $this->belongsToMany(Course::class);
    }

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

// Course.php
public function teacher() {
        return $this->belongsToMany(Teacher::class);
    }

in my database I have data in each of these three tables and I attached teacher and course together in the pivot table

in tinker I tried this:

$course = App\Course::find(1);
// I got here some data

$teacher = App\Teacher::find(1);

$course->teacher;
// I got (id,users_id,about)

$teacher->user;
// I got his data from users table

but when I tried to get the name and email of the teacher :

$course->teacher->user;

it gives me this error: Exception with message 'Property [user] does not exist on this collection instance.'

how can I get this teacher data as user ?

0 likes
5 replies
tykus's avatar

The teacher relation on the Course model is a belongsToMany so it will return a collection, not an individual model instance. You relation names are not helping you here!

If you have a hasMany or belongsToMany then a plural word would better describe the relation, i.e. $course->teachers; as a result you would implicitly understand than you are not dealing with an individual teacher.

amsm1992's avatar

Is there a way to get the teacher data like that? or I have to use selectRaw ?

amsm1992's avatar

I did understand what u said and tried this and it worked:

$course->teacher->first()->user;
Cronix's avatar
Cronix
Best Answer
Level 67

No, you're getting it fine. As @tykus is saying, it's not a single teacher. It's a collection of many teachers. You need to loop over $course->teacher to get the user for each teacher

foreach ($course->teacher as $teacher) {
    $user = $teacher->user;
}

He's also spot on about naming things that make sense for what they represent (teachers (since there are many) vs teacher (doesn't make sense since there are many))

amsm1992's avatar

Thank you very much :) that helped a lot

Please or to participate in this conversation.