khaled amoudi
khaled amoudi

Reputation: 75

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

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?

Upvotes: 1

Views: 2219

Answers (3)

James Morey
James Morey

Reputation: 13

You could do

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

Or

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

Upvotes: 0

MuhammadMP
MuhammadMP

Reputation: 462

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

Upvotes: 1

algmaal
algmaal

Reputation: 1

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

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

Upvotes: 0

Related Questions