Search code examples
laravelquery-builder

Laravel Query Builder left join


can someone please tell me, why i am not able to select section from sections table using left join. i want list of teachers in a table, i am able to access all data from teachers table, but i am not able to see sections using left join. Teacher Table have section_id column, which should access data from sections table on section column.

right now it is giving error when i try to fetch data in view using {{$teacher->section}} Below is my code.

public function listteachers(Request $request)
{
  $teachers = DB::table('teachers')
  ->select('teachers.*')
  ->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
  ->orderBy('pass_exp', 'ASC')
  ->get();
return view('teachers.list',compact('teachers'));
}

Solution

  • You need to select the columns you want from the sections table in your query.

    For example:

    $teachers = DB::table('teachers')
        ->select('teachers.*', DB::raw('sections.name as section_name'))
        ->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
        ->orderBy('pass_exp', 'ASC')
        ->get();