user6562256 user6562256 - 1 year ago 71
SQL Question

appending ->where() clauses based on conditionals

I want to append

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);

if ($test) {
// always true

Answer Source

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) { ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download