Laravel / Eloquent - Undefined variable: idRequest

2

I have two queries looking at the model. The first one is working normally:

        $pedidos =  Pedido::
                orwhere(function($query){
                    $query->where('user_id', $_SESSION['idUsuario'])
                          ->where('status', 'Aberto');
                })
                ->get();

The second however, is returning error from Undefined Variable: requestID.

        $idUserPedido = $pedidos[0]['user_id'];
        $idPedido = $pedidos[0]['id'];

        $produtoDoPedido = PedidoProduto::orwhere(function($query){
            $query->where('id',$_SESSION['idUsuario'])
                  ->where('pedido_id', $idPedido);
        })
        ->get();

When I echo the variable it returns the correct value. The var_dump returns a value as int.

Does anyone know if there are any restrictions to using variables in Eloquent?

    
asked by anonymous 20.10.2017 / 19:27

2 answers

1

The variable $idPedido is set outside the scope of your query, the correct way is to use this:

$idUserPedido = $pedidos[0]['user_id'];
$idPedido = $pedidos[0]['id'];

$produtoDoPedido = PedidoProduto::orwhere(function($query) use($idPedido) {
            $query->where('id',$_SESSION['idUsuario'])
                  ->where('pedido_id', $idPedido);
        })
        ->get();
    
20.10.2017 / 19:30
1

You need to 'import' $idPedido into the anonymous function. Just as the two have their own scope of variables. This is done with keyword use in function:

PedidoProduto::orwhere(function($query) use($idPedido) {

Reading recommends:

Manual - Anonymous functions

In PHP all declared variables are global?

    
20.10.2017 / 19:31