Home > OS >  Laravel query works when given values but not variables
Laravel query works when given values but not variables

Time:06-04

OK, this is driving me insane. Can someone please explain why

Result::query()
    ->where('audit_id', $audit->id)
    ->where('result_type', 'App\Models\Touchpoint')
    ->whereIn('result_id', $tps)
    ->with('result')
    ->join('locations', function ($join) {
        $join->where('locations.id', $location->id);
    })
    ->join('location_weight', function ($join) {
        $join->on('results.result_id', '=', 'location_weight.weight_id')
            ->on('results.result_type', '=', 'location_weight.weight_type')
            ->on('locations.id', '=', 'location_weight.location_id');
    })
    ->get()

doesn't return results when $audit->id = 1 and $location->id = 1, yet

Result::query()
    ->where('audit_id', 1)
    ->where('result_type', 'App\Models\Touchpoint')
    ->whereIn('result_id', $tps)
    ->with('result')
    ->join('locations', function ($join) {
        $join->where('locations.id', 1);
    })
    ->join('location_weight', function ($join) {
        $join->on('results.result_id', '=', 'location_weight.weight_id')
            ->on('results.result_type', '=', 'location_weight.weight_type')
            ->on('locations.id', '=', 'location_weight.location_id');
    })
    ->get()

does return the correct results?

CodePudding user response:

The first codeblock should throw an error. You're referencing a variable from the parent scope ($location) without passing it to the use language construct

// This
->join('locations', function ($join) {
    $join->where('locations.id', $location->id);
})
// should be
->join('locations', function ($join) use ($location) {
    $join->where('locations.id', $location->id);
})
  • Related