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

tsaicharlie93's avatar

Get specific column information from tables in relationship

Hi all, Is there a method to get specific information from tables in relationship?

For example, I have 3 tables

User table Department table school table

User and Department table are in many-to-many relationship so they have a pivot table linking them.

Department include school table id referencing to school names in school table

if I have a user and use belongsToMany method on department, I will get a list of department.

But after that, is there a method that I can use to see what school each department in the list have?

0 likes
3 replies
minjon's avatar

You may try this:

foreach($user->departments as $department)
{
    $school_id = \App\Department::whereId($department->id)->first()->school_id;
    return $school_name  = \App\School::whereId($school_id)->first()->name:
}
Snapey's avatar

the relationships should get you what you need

$schools = $user->departments()->school()->get();

1 like
minjon's avatar
minjon
Best Answer
Level 15

@tsaicharlie93

@ snapey gave me the idea how to simplify my solution:

@foreach ($user->departments as $department)

        <p>{{ $department->name }}: {{ $department->school->name }}</p>

@endforeach 

Please or to participate in this conversation.