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,
 ));

1 Answer 1

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'
                ]]
            ]);
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.