2

Is it possible to use external variables inside the raw function?

$var = 'example';
$res = DB::collection("{$var}_products")->raw(function($collection) {
        global $var; 
        return $collection->aggregate([
                ['$lookup' => [
                    'from' => "{$var}_specifications",
                    'localField' => 'specifications_id',
                    'foreignField' => '_id',
                    'as' => 'specifications'
                ]]
            ]);
        });

I found only an example for an ordinary SQL (https://fideloper.com/laravel-raw-queries)

$someVariable = Input::get("some_variable");
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array(
   'somevariable' => $someVariable,
 ));
VladR
  • 93
  • 8

1 Answers1

3

Use the variable inside the function closure like so

$var = 'example';
$res = DB::collection("{$var}_products")->raw(function($collection) use ($var) {
        return $collection->aggregate([
                ['$lookup' => [
                    'from' => "{$var}_specifications",
                    'localField' => 'specifications_id',
                    'foreignField' => '_id',
                    'as' => 'specifications'
                ]]
            ]);
        });
Ben96
  • 521
  • 1
  • 5
  • 18