get all records of same string under one title in laravel

I am currently getting records from multiple table by using join in laravel. But my issue is that the under the teacher name all records will show those have same teacher name others should be in next table like that e.g

Teacher1 name
id    name       class    subject
1     student1    8         chem 
2     student2    9         phy 
teacher2 name
3     student3    9         chem 
4     student4    11        chem 
teacher3 name
......

here is my laravel view

<table class="table">
      <thead>
       @foreach($students as $student)
        <tr style="background-color: #e9e5e4;">
          <td colspan="4">{{$student->teacher_name}}</td>
        </tr>
      <tr>
        <th>Name</th>
        <th>Class</th>
        <th>Subject</th>
      </tr>
      </thead>
      <tbody>
        <tr>
          <td>{{$student->name }}</td>
          <td>{{$student->class}} </td>
          <td>{{$student->subject }} </td>
        </tr>
      @endforeach
      </tbody>
    </table>

but according to above code I have multiple issues like teacher name is repeating if duplicate entry found in database and I can’t make teacher name unique because I need multiple entry of same name , secondly all records are showing under every teacher. my current output is like that

Teacher1 name
    id    name       class    subject
    1     student1    8         chem 
    2     student2    9         phy 
    3     student3    9         chem 
    4     student4    11        chem 

Teacher2 name
    id    name       class    subject
    1     student1    8         chem 
    2     student2    9         phy 
    3     student3    9         chem 
    4     student4    11        chem 

Answer

I assume that $students is collection. Then you can use the groupBy method. You can rewrite your code like this:

@php
$index = 1;
@endphp

@foreach($students->groupBy('teacher_name') as $teacherName => $subStudents)
<h2>{{$teacherName}}</h2>
<table class="table">
    <thead>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Class</th>
            <th>Subject</th>
        </tr>
    </thead>
    <tbody>
        @foreach($subStudents as $student)
            <tr>
                <td>{{$index }}</td>
                <td>{{$student->name }}</td>
                <td>{{$student->class}} </td>
                <td>{{$student->subject }} </td>
            </tr>
        @php
            $index++;
        @endphp
        @endforeach
    </tbody>
</table>
@endforeach

Let me know if that answer your question.