Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rretzko's avatar
Level 15

Unique() not working on collection

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!

0 likes
8 replies
MichalOravec's avatar

I assume $students is a collection and currentTeacher is a relationship to Teacher model.

$uniqueTeachers = $students->pluck('currentTeacher')->unique();
Rretzko's avatar
Level 15

@MichalOravec Thanks! $students is a collection, currentTeacher is a function which identifies the current teacher from the student's collection of teachers ($student->teachers) and returns the single object. On my next release, I may have currentTeacher as a property, but not currently.

Rretzko's avatar
Level 15

Thanks @MichalOravec I do express it as a property, but it is a function: getCurrentTeacherAttribute() . I tried inserting it as suggested: $students->pluck('currentTeacher')->unique() and it also returns 157 rows.

Snapey's avatar
Snapey
Best Answer
Level 122

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');
jlrdw's avatar

Are you trying to get a teacher or a list of students with a certain teacher.

Rretzko's avatar
Level 15

@jlrdw In this case, I was building a list of unique teachers from a collection of students.

Please or to participate in this conversation.