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

Kubca's avatar
Level 1

Relationship between two table - With construction

I have three tables

course_registrations
| id | user_id | created_at|

users
| id | name | password | workplace_id |

workplaces
| id | name |

I need get all items from courseRegistration, with user, and workplace name.

I have this query, but not working correctly, workplace only show int of workplace_id

CourseRegistration::with('user')->with('workplace')->get();

My relations is:

public function user(){
    return $this->hasOne('App\User', 'id', 'user_id');
}

--

public function workplace()
{
    return $this->hasOne(Workplace::class, 'id', 'workplace_id');
}

What is bad? How to fix it?

Thanks.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

workplace belongs to user so you need to do;

CourseRegistration::with('user.workplace')->get();

since (I assume) workplace is a method on User model

remember when the data is returned, workplace will be under user so the name of the workplace is with $course_registration->user->workplace->name

1 like

Please or to participate in this conversation.