I assume $students is a collection and currentTeacher is a relationship to Teacher model.
$uniqueTeachers = $students->pluck('currentTeacher')->unique();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi All - I've implemented a workaround by storing the id into an array and then using in_array() function, but I think Laravel's Unique() function should have worked, but I couldn't get this simple function to perform.
Here's the scenario: I have a collection of students. Student/Teacher is a many-to-many relationship. I'm looking for a collection of unique teachers.
Here's the code:
//initialize empty collection
$teachers = collect();
//iterate through students
foreach($students AS $student) {
//retrieve current teacher; returns teacher object
$teacher = $student->currentTeacher;
//push object into collection
$teachers->push($teacher);
}
//remove the duplicates
$uniqueteachers = $teachers->unique();
In the case above, $teachers return 157 rows and $uniqueteachers returns 157 rows. My workaround implementation is:
//initialize empty collection
$teachers = collect();
//initialize storage array for ids
$ids = [];
foreach($students AS $student) {
$teacher = $student->currentTeacher;
if(! in_array($teacher->user_id, $ids)) {
//update storage array
$ids[] = $teacher->user_id;
//update teacher collection
$teachers->push($teacher);
}
}
In this case, $teachers returns 48 rows. It seems like $teachers->unique() should do the work of the workaround, but I can't figure out what I'm doing wrong. Thanks for your better eyes and suggestions!
if the teachers are models (its a collection of models) then the collection method unique needs to know which field it should consider for uniqueness, ie
$uniqueteachers = $teachers->unique('id');
Please or to participate in this conversation.