Search code examples
phpmysqllaravel-5fluent

appending ->where() clauses based on conditionals


I want to append where clauses to the query based on certain conditions, the problem is that the way I check if it returned a row from the database it always returns true.

If I do a query in one line like so:

$test= DB::table('users')->where('email', $email)->where('password', $password)->first();

It works as expected, if a row is found it is true and vice versa, but if I append to the query like so, it is always true (which makes sense, but how do I check that it actually returned something from the db?):

$test= DB::table('users');
$test->where('email', $email);
 $test->where('password', $password);
$test->first();

if ($test) {
       // always true
 }

Solution

  • The statement $test->first(); executes the query and returns the first result, but you aren't assigning that result to anything, so $test is still just the query object, which will always evaluate to true as you are seeing. If you assign it to something else and then check that, it should work.

    $example = $test->first();
    
    if ($example) { ...