menu

Questions & Answers

Laravel unexpected result with WHERE and EXISTS

I have made a few Laravel application (Mainly Laravel Zero) and I have not seen this type of issue before.

I have an array which consists of 3 strings, and 3 indexes. The plan is to foreach through this array to check if the values already exist in the database, I have never had issues with Eloquent before but it appears to be having some unexpected results?

foreach ($transaction as $transactions)
{
            // Check if TX exists
            $exists = $database->where('txid', '=', $transactions['txid'])->toSql();
            echo $exists . "\n"; 
}

Each time it goes around the loop, the query changes - the first iteration returns true when using exists() but anything after that is false when it should be true.

Output results of toSql();

select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ? and `txid` = ?

Expected results of toSql();

select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ?
Comments:
2023-01-11 09:29:33
That is happening because you are adding the same stuff to the $database Eloquent Builder class...
2023-01-11 09:29:33
@matiaslauriti Back to the books it seems. Resolved. Thank you.
Answers(1) :

What is $database in your case? make sure $database is initialized every time your loop is executed as new for example

assuming your $database is transaction's model object

foreach ($transaction as $transactions)
{
    $database = new Transaction();
    // Check if TX exists
    $exists = $database->where('txid', '=', $transactions['txid'])->toSql();
    echo $exists . "\n"; 
}    
Comments:
2023-01-11 09:29:33
Thank you. Matiaslauriti previously commented and this was the issue.