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 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';
Sign up to request clarification or add additional context in comments.

Comments

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

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

1 Comment

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
0

You could do

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

Or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.