1

Here my code :

$classroom_ids = $user->classrooms->pluck('id');
            $classrooms = Classroom::with('students')
                ->whereIn('id', $classroom_ids)
                ->get();

I try to get all cumulated students on twos classrooms records.

I tried to use ->pluck('students') without success.

Here the classrooms datas :

0 => [
  'id' : 1,
  'students': Array of students
],
1 => [
  'id' : 2,
  'students': Array of students
],

How to get all students in one array ? Thanks

2
  • please show your models and relationships Commented Feb 25, 2021 at 17:14
  • I think your query base model should be of Student instead of Classroom like Student::whereIn('class_id', $user->classroom->pluck('id'))->get() Commented Feb 25, 2021 at 17:20

2 Answers 2

4

Use map with flatten.

$classrooms = Classroom::with('students')
            ->whereIn('id', $classroom_ids)
            ->get()
            ->map(function($classroom){
                return $classroom->students;
            })
            ->flatten()
            ->toArray();

If students to classroom is a many to many you can use keyBy there are no duplicates.

$classrooms = Classroom::with('students')
            ->whereIn('id', $classroom_ids)
            ->get()
            ->map(function($classroom){
                return $classroom->students;
            })
            ->flatten()
            ->keyBy('id')
            ->toArray();
Sign up to request clarification or add additional context in comments.

1 Comment

flatMap if you please :)
0

Here the solution (inspired by Jed Lynch answer) :

$classroom_ids = $user->classrooms->pluck('id');
            $users = Classroom::with('students')
                ->whereIn('id', $classroom_ids)
                ->get()
                ->pluck('students')
                ->flatten();

Thank's for your help !

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.