Lumen AND OR conditions in Where clause

7.8k Views Asked by At

I am trying to run following query in Lumen Framework:

SELECT * FROM user WHERE (username = $username OR email = $username) AND password = $password AND flag = 1;

My Lumen code:

$login =  User::where('pass', '=', md5($pass))
               ->where('flag', '=', $flag)
               ->where('username', '=', $username)
               ->orWhere('email', '=', $username)->first();

Somehow this code always return true and bypass the login. What is wrong in that query?

When I remove orWhere from query it works perfect for username.

3

There are 3 best solutions below

5
On BEST ANSWER

If you want to group the two conditions (username and email) into a single condition (surrounded by parenthesis), you will have to do it like this:

User::where('pass', '=', md5($pass))
    ->where('flag', '=', $flag)
    ->where(function ($query) use ($username) {
        $query->where('username', '=', $username)
              ->orWhere('email', '=', $username);
    })->first();

Here is the documentation on advanced where conditions for the Laravel query builder (which Lumen uses).

0
On

Follow laravel advance where http://laravel.com/docs/4.2/queries#advanced-wheres

User::where('pass', '=', md5($pass))
->where('flag', '=', $flag)
->where(function ($query) use ($username) {
    $query->where('username', '=', $username)
          ->where('email', '=', $username);
})->first();
0
On

It seems to me that what you want is this:

User::where('pass', '=', md5($pass))
    ->where('flag', '=', $flag)
    ->where(function ($query) use ($username) {
        $query->where('username', '=', $username)
              ->orWhere('email', '=', $username);
    })->first();

Also please don't use md5, try re hashing all of your passwords with bcrypt()