dimanche 26 juin 2016

How to fetch groupBy using eloquent Laravel

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.

StudentCourseController

public function show($studentId, $courseId)
{
    $student = Student::findOrFail($studentId);
    $course = Course::with(['curriculum.subjects' => function($query){
        $query->get()->groupBy('sem_offered')->toArray();
    }])->findOrFail($courseId);

    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)

    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>

@endforeach



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire