Laravel/Eloquent - Undefined variable: idPedido

Asked

Viewed 218 times

2

I have two queries searching 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 Undefined Variable error: idPedido.

        $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. var_dump returns a value as int.

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

  • Needs to import' $idPedido into the anonymous function.

2 answers

2


Variously $idPedido is defined outside the scope of your query, the correct way is to use it like 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();

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.