1

I have a one-to-many relationship between group and students and I want to get all students of some groups so I do this:

public function getStudentsOfGroups()
{
    $groups = Auth::user()->groups;
    foreach($groups as $group){
        $students  = $group->students;
    }

    return view('teacher.home', compact('students'));
}

but it doesn't get the data I need, so what can I do instead?

1
  • 2
    $students[] = $group->students; otherwise you will only see the data from the last iteration
    – RiggsFolly
    Commented May 26, 2022 at 9:31

3 Answers 3

1

Try this:

$students = Student::whereHas('groups', function (Builder $query) {
    $query->where('your_foreign_key_on_groups', auth()->id());
})
->get();

NOTE: When you want to add something to an array, you should use this syntax:

$array[] = 'a new element';
0
    public function getStudentsOfGroups()
{
    $groups = Auth::user()->groups;
    foreach($groups as $group){
        $students[]  = $group->students;
    }

    return view('teacher.home', compact('students'));
}
1
  • Hi, please consider adding more details as to how this helps solve the question. The more detail you can add the more helpful your answer will be to other's. Please consider reviewing the how to answer article stackoverflow.com/help/how-to-answer Commented May 26, 2022 at 21:24
0

You could do

$results = Auth::user()->groups->students

Or

$results = Group::with('students')->where('user_id', Auth::user()->id;

Not the answer you're looking for? Browse other questions tagged or ask your own question.