Geoff
Geoff

Reputation: 6649

Laravel Lumen eloquent left join returns joined table data rather than primary able data

I have two tables company and courses table The table has the following fields

 companies table
  id, full_name, email, deleted_at

and courses table

 courses table
  id, company_id, course_name,deleted_at

Now i would like to retrieve all courses which company is not deleted. So in my controller i have added

public function index(Request $request){

  $query = Courses::query();
  $query = $query->leftJoin('companies','companies.id','=','courses.company_id');
  $query->whereNull('companies.deleted_at');
  if($request->get('filter_name')){
    $query = $query->where('courses.name', 'like', '%' . $request->get('filter_name') . '%');
  }
 
  return  response()->json($query->paginate($request->get("perPage")));  
}
    

When i run the above it returns companies data rather than courses. Where am i going wrong or what am i missing out?

Upvotes: 0

Views: 458

Answers (1)

MONSTEEEER
MONSTEEEER

Reputation: 580

If you have use eager loading in both of your model, you can use this kind of approach.

$all_course = Courses::with(['company', function($query) {
                            return $query->whereNotNull('deleted_at');
                       }])->get();

As you can see, I query in the Courses model to return all the courses but I added some filter in the company relationship. where in I used whereNotNull to get only the company that's not deleted.

Upvotes: 0

Related Questions