Question: I am relatively new to the database world so bear with me. I'm just trying to add foreign key constraints and I keep getting error 1215 "cannot add foreign key constraint".

```
  CREATE TABLE InProcessSamples
  (
  SampleNumber Int(6),
  WorkOrder Int(8),
  DueDate Date,
  BeginsTesting Date,
  FinishedTesting Date,
  CONSTRAINT fk_sample_number FOREIGN KEY(SampleNumber) REFERENCES AllRecords(SampleNumber),
  CONSTRAINT fk_work_order FOREIGN KEY(WorkOrder) REFERENCES SamplesReceived(WorkOrder)
  );

  CREATE TABLE SamplesReceived
  (
  WorkOrder Int(8) PRIMARY KEY,
  SampleNumber Int(6),
  RecTimeStamp DateTime,
  PartNumber Int(10),
  Description Char(36),
  CONSTRAINT fk_sample_number FOREIGN KEY(SampleNumber) REFERENCES AllRecords(SampleNumber),
  CONSTRAINT fk_part_number FOREIGN KEY(PartNumber) REFERENCES PartNumbers(PartNumber)
  ); 

  CREATE TABLE AllRecords
  (
  SampleNumber Int(6) PRIMARY KEY,
  WorkOrder Int(8),
  DueDate Date,
  BeginsTesting Date,
  FinishedTesting Date,
  RecTimeStamp DateTime,
  MeasurementOne Double,
  MeasurementTwo Double,
  PassDielectric Char(3),
  PassedAllTest Char(3),
  CONSTRAINT fk_work_order FOREIGN KEY(WorkOrder) REFERENCES SamplesReceived(WorkOrder),
  CONSTRAINT fk_part_number FOREIGN KEY(PartNumber) REFERENCES PartNumbers(PartNumber)
  );

  CREATE TABLE PartNumbers
  (
  PartNumber Int(10) PRIMARY KEY,
  Description Char(36)
  );

```

Answer: 
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!