Home > Mobile >  How can i fetch data in a foreach() loop in Laravel controller
How can i fetch data in a foreach() loop in Laravel controller

Time:05-26

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?

CodePudding user response:

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';

CodePudding user response:

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

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

CodePudding user response:

You could do

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

Or

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