3 years ago

How to fetch groupBy using eloquent

Posted 3 years ago by jay_gorio

I want to fetch all subjects that belongs to each semester. However I cannot find ways to do that. For example in my view I want to fetch subjects that are offered in fist first-sem. Also display below subjects offered in first second-sem. Here is my code.


public function show($studentId, $courseId)
    $student = Student::findOrFail($studentId);
    $course = Course::with(['curriculum.subjects' => function($query){

    return view('students.show',compact('student','course'));

Curriculum Model

class Curriculum extends Model
    protected $fillable = ['name', 'description'];
    public function course()
        return $this->hasOne(Course::class);

    public function subjects()
        return $this->belongsToMany(Subject::class)->withPivot('sem_offered','grade','prerequisite');

Subject Model

class Subject extends Model
    public function curricula()
        return $this->belongsToMany(Curriculum::class)->withPivot('sem_offered','grade');

Course Model

   class Course extends Model
    protected $fillable = ['curriculum_id', 'name' ,'description'];
    public function curriculum()
        return $this->belongsTo(Curriculum::class);


Here is my view

        @foreach($course->curriculum->subjects as $subject)

        <td>{{ $subject->subject_code }}</td>
        <td>{{ $subject->subject_description }}</td>
        <td>{{ $subject->lecture_units }}</td>
        <td>{{ $subject->lab_units }}</td>
        <td>{{ $subject->pivot->grade }}</td>


Please sign in or create an account to participate in this conversation.