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:
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
@ 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.