Fernando Preciado
Fernando Preciado

Reputation: 305

Accessing id From a Route

I'm working with mongo in laravel with jenssegers and I want to $match with the current id in this function inside my controller:

public function updatearray(Request $request, $id)
{
    $id = new \MongoDB\BSON\ObjectID($id);
    # return var_dump($id); 
    # return object(MongoDB\BSON\ObjectID)#179 (1) 
    # { ["oid"]=> string(24)"594dd6ccbb7de924c0005585" }
    $result = Work::raw(function($collection) {
        return $collection->aggregate(
            array(
                array('$match' => array( "_id" => $id )),
                array('$project' =>
                    array( "Monto" => array('$sum' => '$Abonos.Monto') )
                )
            )
        );
    });
}

And I get.

(1/1) ErrorExceptionUndefined variable: id.

But if I return $id before the code enter to the raw function it return the proper current id. If I hardcore the ObjectId inside the raw query it works.

Am I missing something?

Upvotes: 0

Views: 78

Answers (1)

linktoahref
linktoahref

Reputation: 7992

ErrorExceptionUndefined variable: id

because you aren't passing the id to the closure

public function updatearray(Request $request, $id)
{
    $id = new \MongoDB\BSON\ObjectID($id);
    $result = Work::raw(function($collection) use ($id) {
        return $collection->aggregate(
            array(
                array('$match' => array( "_id" => $id )),
                array('$project' =>
                    array( "Monto" => array('$sum' => '$Abonos.Monto') )
                )
            )
        );
    });
}

Upvotes: 1

Related Questions