I am building an app that handles courses, study groups and students. Courses have a one-to-many relationship with groups, and groups have a many-to-many relationship with profiles.
Right now I am building the user dashboard. This dashboard shows the groups that the authenticated user is a part of. I would like to display the names of the other students that are part of each group. The method that gets the user-related groups is the following.
public function show()
{
$groups = auth()->user()->profile->isStudentInGroup()->orderBy('course_id')->get();
return view('dashboard', compact('groups'));
}
In my dashboard.blade.php, I can display the ids of the other students like this :
@foreach($groups as $group)
<div>
{{ $group->course->name }} {{ $group->teacher_name }} {{ $group->weekday }} {{ Carbon::parse($group->start_time)->format('H:i') }}
</div>
<div>
@foreach($group->hasStudents as $student)
{{ $student->id }}
@endforeach
</div>
@endforeach
As I said, I would like to display their names instead of their ids. I can't access that property from the template file because my hasStudents() relationship only stores the group_id and the profile_id. I would also like to have a groups.index route for the admin, and I would like to reuse that functionality there. So I have the intuition that I should not write that logic inside of my dashboard controller.
What would be a good design to achieve that? Should I make my groups list into a component and bring the names to the component via the component class? Is there a better or cleaner way to do it?
Thanks in advance.
EDIT :
I have found a way to display the names but it's very bad. I welcome all feedback.
In my controller :
public function show()
{
$groups = auth()->user()->profile->isStudentInGroup()->orderBy('course_id')->get();
$profiles = Profile::get();
return view('dashboard', compact('groups', 'profiles'));
}
In my view :
@foreach($groups as $group)
<div>
{{ $group->course->name }} {{ $group->teacher_name }} {{ $group->weekday }} {{ Carbon::parse($group->start_time)->format('H:i') }}
</div>
<div>
@foreach($group->hasStudents as $student)
{{ $student->id }} {{ $profiles[$student->id -1]->user->name }}
@endforeach
</div>
@endforeach