Tuesday, March 7, 2017

How to output data using query builder while eliminating duplicates

I have a table of results where there is adm_no, subject_id, exam_id and score fields. I inserted the data using the updateOrCreate method in laravel 5.4.

When I fetch the data I still get duplicates. e.g. when a user inserts marks for instance 2 students for a given subject and repeats it for the same students and subject I should get the latest row of all results.

Here is a sample of my query:

public function searchStudent()
{
    $exam = Exam::all();
    $term = Term::all();

    $a = Input::get('adm_no');
    $e = Input::get('exam_id');
    $t = Input::get('term_id');
    $y = Input::get('year');

    $results = DB::table('results')
        ->select(DB::raw('DISTINCT(subject_id)'))
        ->where('adm_no', 'LIKE', '%' . $a . '%')
        ->where('exam_id','LIKE', '%' . $e . '%')
        ->where('term_id', 'LIKE', '%' . $t . '%')
        ->where('year', 'LIKE', '%' . $y . '%')
        ->orderBy('created_at', 'desc')
        ->get();

    dd($results); 
}



via David Musyoka

Advertisement