dont you have a relationship, 'attendances' on the user model?
Then you could just
$users = User::with('attendances')->get();
and automatically get the attendances nested under the user model.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a table named Attendences with columns student_id, date , status. From that table i need to show the attendances of students. Here is my table:
id | student_id | date | status
1 1 31-7-22 Present
2 1 01-8-22 Present
3 2 27-7-22 Absent
1 2 28-7-22 Absent
2 2 29-7-22 Present
Here's my code in Controller:
public function viewall(){
$attendances = attendance::get();
$users = student::get();
foreach($users as $user)
{
$student['id'] = $user->id;
$student['name'] = $user->name;
foreach($attendances as $attendance)
{
if($attendance->student_id == $user->id)
{ //return "ih";
//dd($attendance->student_id);
$attend_2['student_id'] = $attendance->student_id;
$attend_2['attendance'] = $attendance->status;
$attend_2['date'] = $attendance->date;
$attend[] = $attend_2;
}
}
$student['attendance'] = $attend;
$final[] = $student;
}
dd($final) ;
}
But output is messed up. Can anyone help? Here is the output
array:5 [▼
0 => array:3 [▼
"id" => 1
"name" => "Akhil"
"attendance" => array:2 [▼
0 => array:3 [▼
"student_id" => 1
"attendance" => "Present"
"date" => "2022-08-01"
]
1 => array:3 [▼
"student_id" => 1
"attendance" => "Present"
"date" => "2022-07-31"
]
]
]
1 => array:3 [▼
"id" => 2
"name" => "Amal"
"attendance" => array:5 [▼
0 => array:3 [▼
"student_id" => 1
"attendance" => "Present"
"date" => "2022-08-01"
]
1 => array:3 [▼
"student_id" => 1
"attendance" => "Present"
"date" => "2022-07-31"
]
2 => array:3 [▼
"student_id" => 2
"attendance" => "Absent"
"date" => "2022-07-27"
]
3 => array:3 [▼
"student_id" => 2
"attendance" => "Absent"
"date" => "2022-07-28"
]
4 => array:3 [▼
"student_id" => 2
"attendance" => "Present"
"date" => "2022-07-29"
]
]
]
Please or to participate in this conversation.