too long

I have a big query which has a nested query. I want to know how to write it so that it's not cluttered. What I tried was creating query objects

//get the latest joined employee per department
$q1   = Employee::where('job', 'assistant')
                   ->groupBy('dept_id')
                   ->select(DB::raw('MAX(empid) as empid'));
//fetch his course ID
$q2    = Employee::whereIn('empid', function($query){
                                           $query->$q1;
                                       })
                   ->where('university', 'LIKE', '%UCLA%')
                   ->select('course_id')
                   ->distinct()
                   ->get()->lists('course_id'); 

I am getting this error

[Symfony\Component\Debug\Exception\FatalThrowableError]  
  Cannot access empty property

How should I do it?

You need to inherit your variable from your parent scope in your anonymous function. It's possible with use, like so:

function($query) use ($q1) {
    // use $q1 here
}

Read about use (Example #3 Inheriting variables from the parent scope) here: http://www.php.net/manual/en/functions.anonymous.php

You should do it in this way:

$q1   = Employee::where('job', 'assistant')
               ->groupBy('dept_id')
               ->select(DB::raw('MAX(empid) as empid'));

$q2    = Employee::whereIn('empid', function($query) use($q1) {
                                       $query->where('id', $q1); // <---- Do it like this
                                   })
               ->where('university', 'LIKE', '%UCLA%')
               ->select('course_id')
               ->distinct();

Hope this helps!